按嵌套键合并嵌套字典?
我有几个字典,它们里面有不同的键,也有一些相同的键,里面还有嵌套的字典,这些嵌套字典也有不同和相同的键。下面是一个简化的例子,实际上这些字典有成千上万的键。
{1:{"Title":"Chrome","Author":"Google","URL":"http://"}}
{1:{"Title":"Chrome","Author":"Google","Version":"7.0.577.0"}}
{2:{"Title":"Python","Version":"2.5"}}
我想把它们合并成一个字典。
{1:{"Title":"Chrome","Author":"Google","URL":"http://","Version":"7.0.577.0"},
2:{"Title":"Python","Version":"2.5"}}
我可以遍历这两个字典,比较它们的键,然后用update
方法更新嵌套字典,但可能还有更有效率或者说更“python风格”的做法。如果没有,那哪种方法是最有效的呢?
嵌套字典的值不需要进行比较。
4 个回答
0
试试用一个叫 NestedDict
的东西。首先,你需要安装一下这个库,链接在这里:ndicts
pip install ndicts
然后
from ndicts.ndicts import NestedDict
my_dicts = [
{1:{"Title":"Chrome","Author":"Google","URL":"http://"}},
{1:{"Title":"Chrome","Author":"Google","Version":"7.0.577.0"}},
{2:{"Title":"Python","Version":"2.5"}},
]
nd = NestedDict()
for my_dict in my_dicts:
nd.update(NestedDict(my_dict))
这样你就可以把结果得到一个字典形式
>>> nd.to_dict()
{1: {'Title': 'Chrome', 'Author': 'Google', 'Version': '7.0.577.0', 'URL': 'http://'},
2: {'Title': 'Python', 'Version': '2.5'}}
2
根据你的例子,看起来你可以这样做:
from collections import defaultdict
mydict = defaultdict(dict)
for indict in listofdicts:
k, v = indict.popitem()
mydict[k].update(v)
6
抱歉,我无法处理该请求。