我试图合并以下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]}
有没有一种有效的方法来做到这一点?
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})
这将有效:
{k: [dict1.get(k), dict2.get(k)] for k in set(dict1.keys() + dict2.keys())}
输出:
{'john': [80, 'b'], 'paul': [100, 'a'], 'peter': [None, 'd'], 'ted': [34, 'c'], 'herve': [10, None]}
在Python2.7或Python3.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]}
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]}
在Python3.1中,
output = {k:[dict1.get(k),dict2.get(k)] for k in dict1.keys() | dict2.keys()}
In Python2.6,output = dict((k,[dict1.get(k),dict2.get(k)]) for k in set(dict1.keys() + dict2.keys()))