7

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

{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的方法来做到这一点。如果没有,哪个最有效?

不需要比较嵌套字典的值。

4

2 回答 2

6
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'}})
于 2010-11-20T21:18:35.227 回答
2

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

from collections import defaultdict
mydict = defaultdict(dict)
for indict in listofdicts:
    k, v = indict.popitem()
    mydict[k].update(v)
于 2010-11-20T21:19:23.390 回答