通过嵌套键合并嵌套词典?

时间:2010-11-20 21:03:23

标签: python dictionary python-2.5

我有几个带有不同和常用键的字典,以及嵌套字典中的不同和常用键。下面是一个简化的例子,实际的词典有数千个键。

{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嵌套词典,但可能有更高效的方法,或者 pythonic ,这样做。如果没有,哪个最有效?

无需比较嵌套字典的值。

2 个答案:

答案 0 :(得分:5)

from collections import defaultdict

mydicts = [
   {1:{"Title":"Chrome","Author":"Google","URL":"http://"}},
   {1:{"Title":"Chrome","Author":"Google","Version":"7.0.577.0"}},
   {2:{"Title":"Python","Version":"2.5"}},
]

result = defaultdict(dict)

for d in mydicts:
    for k, v in d.iteritems():
        result[k].update(v)

print result

defaultdict(<type 'dict'>, 
    {1: {'Version': '7.0.577.0', 'Title': 'Chrome', 
         'URL': 'http://', 'Author': 'Google'}, 
     2: {'Version': '2.5', 'Title': 'Python'}})

答案 1 :(得分:2)

从您的示例中,您可以执行以下操作:

from collections import defaultdict
mydict = defaultdict(dict)
for indict in listofdicts:
    k, v = indict.popitem()
    mydict[k].update(v)
相关问题