[英]merging Python dictionaries
I am trying to merge the following python dictionaries as follow:我正在尝试合并以下 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]}
Is there an efficient way to do this?有没有一种有效的方法来做到这一点?
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})
This will work:这将起作用:
{k: [dict1.get(k), dict2.get(k)] for k in set(dict1.keys() + dict2.keys())}
Output:输出:
{'john': [80, 'b'], 'paul': [100, 'a'], 'peter': [None, 'd'], 'ted': [34, 'c'], 'herve': [10, None]}
In Python2.7 or Python3.1 you can easily generalise to work with any number of dictionaries using a combination of list, set and dict comprehensions!在Python2.7或Python3.1 中,您可以使用列表、集合和字典推导式的组合轻松泛化以使用任意数量的字典!
>>> 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 doesn't have set comprehensions or dict comprehensions 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]}
In Python3.1,
在 Python3.1 中,
output = {k:[dict1.get(k),dict2.get(k)] for k in dict1.keys() | dict2.keys()}
output = dict((k,[dict1.get(k),dict2.get(k)]) for k in set(dict1.keys() + dict2.keys()))
Using chain.from_iterable (from itertools) you can avoid the list/dict/set comprehension with:使用chain.from_iterable (来自itertools)你可以避免list/dict/set理解:
dict(chain.from_iterable(map(lambda d: d.items(), list_of_dicts])))
It can be more or less convenient and readable than double comprehension, depending on your personal preference.根据您的个人喜好,它可能比双重理解更方便或更易读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.