假设我有两个字典,它们的值都是列表(或者集合也可以,因为它们的内容是唯一的)。例如:
dic1 = {'math': ['algebra', 'trigonometry', 'geometry']}
dic2 = {'math': ['calculus'], 'science': ['physics']}
dic2.update(dic1)我想要的输出是:
{'math': ['algebra', 'trigonometry', 'geometry', 'calculus'], 'science': ['physics']}但我得到的却是:
{'math': ['algebra', 'trigonometry', 'geometry'], 'science': ['physics']}本质上,我希望在合并两个字典时合并内容(我不想覆盖,而是同时保留两者)。有没有简单的方法可以做到这一点?注意:在我给出的这个例子中,只有两个字典。虽然我还没有编写代码,但我最终还是希望遍历几个字典,并在循环中执行合并/更新过程,这可能对提出一种方法很有帮助。
发布于 2017-07-23 00:26:10
这可以用一个简单的一行代码来表示:
>>> {k: dic1.get(k, []) + dic2.get(k, []) for k in (set(dic1) | set(dic2))}
{'science': ['physics'], 'math': ['algebra', 'trigonometry', 'geometry', 'calculus']}这结合了三种技术:
the union of two sets将键合并并消除。dict.get()方法提供缺省的空键列表。
Python的核心工具包经常为基本的数据操作问题提供优雅的解决方案。我经常惊讶于这些工具是如此完美地结合在一起。
这有什么帮助:-)
发布于 2017-07-22 08:13:05
要在合并多个列表字典时避免重复,请执行以下操作:
def updateDict(dict1, dict2):
for key in dict1:
if key in dict2:
prev_values = set(dict1[key]) # create set to retain only unique values in list
prev_values.update(dict2[key])
dict1[key] = list(prev_values)发布于 2017-07-22 08:12:42
dict1 = {'math': ['algebra', 'trigonometry', 'geometry']}
dict2 = {'math': ['calclus'], 'science': ['physics']}
for key, value in dict1.items():
dict2.setdefault(key, []).extend(value)
>>> print(dict2)
{'science': ['physics'], 'math': ['calclus', 'algebra', 'trigonometry', 'geometry']}如果您希望保留这两个字典值,请执行以下操作
from copy import deepcopy
dict1 = {'math': ['algebra', 'trigonometry', 'geometry']}
dict2 = {'math': ['calclus'], 'science': ['physics'], 'lol':['lol1']}
dict3 = deepcopy(dict2)
for key, value in dict1.items():
dict3.setdefault(key, []).extend(value)
>>>print(dict2)
{'science': ['physics'], 'math': ['calclus']}
>>>print(dict3)
{'science': ['physics'], 'math': ['calclus', 'algebra', 'trigonometry', 'geometry']}https://stackoverflow.com/questions/45248348
复制相似问题