合并Python词典

Joe*_*oey 23 python merge dictionary list data-structures

我试图合并以下python词典如下:

dict1= {'paul':100, 'john':80, 'ted':34, 'herve':10}
dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'}

output = {'paul':[100,'a'],
          'john':[80, 'b'],
          'ted':[34,'c'],
          'peter':[None, 'd'],
          'herve':[10, None]}
Run Code Online (Sandbox Code Playgroud)

有没有一种有效的方法来做到这一点?

Ale*_*lli 21

output = {k: [dict1[k], dict2.get(k)] for k in dict1}
output.update({k: [None, dict2[k]] for k in dict2 if k not in dict1})
Run Code Online (Sandbox Code Playgroud)


Nad*_*mli 15

这将有效:

{k: [dict1.get(k), dict2.get(k)] for k in set(dict1.keys() + dict2.keys())}
Run Code Online (Sandbox Code Playgroud)

输出:

{'john': [80, 'b'], 'paul': [100, 'a'], 'peter': [None, 'd'], 'ted': [34, 'c'], 'herve': [10, None]}
Run Code Online (Sandbox Code Playgroud)


Joh*_*ooy 8

Python2.7Python3.1中,您可以使用list,set和dict comprehension的组合轻松推广使用任意数量的字典!

>>> dict1 = {'paul':100, 'john':80, 'ted':34, 'herve':10}
>>> dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'}
>>> dicts = dict1,dict2
>>> {k:[d.get(k) for d in dicts] for k in {k for d in dicts for k in d}}
{'john': [80, 'b'], 'paul': [100, 'a'], 'peter': [None, 'd'], 'ted': [34, 'c'], 'herve': [10, None]}
Run Code Online (Sandbox Code Playgroud)

Python2.6没有集合理解或字典理解

>>> dict1 = {'paul':100, 'john':80, 'ted':34, 'herve':10}
>>> dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'}
>>> dicts = dict1,dict2
>>> dict((k,[d.get(k) for d in dicts]) for k in set(k for d in dicts for k in d))
{'john': [80, 'b'], 'paul': [100, 'a'], 'peter': [None, 'd'], 'ted': [34, 'c'], 'herve': [10, None]}
Run Code Online (Sandbox Code Playgroud)