我的合并词典代码出错了。这就是我得到的:
output1 = {'children':
{'children':
{'children':
{'name': 'thriller.mp3', 'type': 'file'},
'name': 'pop',
'type': 'folder'},
'name': 'test_pendrive',
'type': 'folder'},
'name': 'media',
'type': 'folder'}
output2 = {'children':
{'children':
{'children':
{'name': 'paranoid.mp3', 'type': 'file'},
'name': 'metal',
'type': 'folder'},
'name': 'test_pendrive',
'type': 'folder'},
'name': 'media',
'type': 'folder'}
我的代码目前看起来像这样:
from collections import defaultdict
l1 = list(output2.items())
l2 = list(output.items())
l3 = l1+l2
d1 = defaultdict(list)
for k,v in l3:
d1[k].append(v)
给出了输出:
{
"name": ["media", "media"],
"type": ["folder", "folder"],
"children": [{
"name": "test_pendrive",
"type": "folder",
"children": {
"name": "dance",
"type": "folder",
"children": {
"name": "billie_jean.mp3",
"type": "file"
}
}
},
{
"name": "test_pendrive",
"type": "folder",
"children": {
"name": "pop",
"type": "folder",
"children": {
"name": "thriller.mp3",
"type": "file"
}
}
}
]
}
这几乎就是我想要的。我的最终目标是:
{
"name": ["media", "media"],
"type": ["folder", "folder"],
"children": [{
"name": "test_pendrive",
"type": "folder",
"children": [{
"name": "dance",
"type": "folder",
"children": {
"name": "billie_jean.mp3",
"type": "file"
}
},{
"name": "pop",
"type": "folder",
"children": {
"name": "thriller.mp3",
"type": "file"
}
}]
}
}
我哪里错了?这是实现这一目标的最佳方法吗?提前致谢。