【发布时间】:2018-05-16 22:01:29
【问题描述】:
我有两本词典。
我需要根据键:值对将它们合并在一起。如果第一个或第二个字典中的任何 key:value 项不匹配,它们将作为单独的对添加到最终字典中。
【问题讨论】:
-
请不要破坏您的帖子。
标签: python dictionary merge
我有两本词典。
我需要根据键:值对将它们合并在一起。如果第一个或第二个字典中的任何 key:value 项不匹配,它们将作为单独的对添加到最终字典中。
【问题讨论】:
标签: python dictionary merge
可能效率不高,但幼稚的方法可能是遍历每个字典中的项目并添加新字典:
Dict1 = {'a': [1, 2, 3], 'b': [5], 'c': [5, 6, 9]}
dict2 = {'a': [4], 'b': [8, 9, 0], 'd': [10, 14, 13]}
# to store final result of dictionary
result = {}
# iterate through each dictionary in list
for dictionary in [Dict1, dict2]:
# iterate through key value of dictionary items
for k,v in dictionary.items():
# if key is already in result dictionary then extend new values
if k in result.keys():
result[k].extend(v)
# else if key is not in dictionary then add key with the first value
else:
result[k] = v
print(result)
结果:
{'d': [10, 14, 13], 'a': [1, 2, 3, 4], 'b': [5, 8, 9, 0], 'c': [5, 6, 9]}
注意正如@chepner 在下面的 cmets 中指出的那样,上述解决方案更改了 Dict1,因此,使用 deepcopy 将避免它,而其他是 .keys() 在检查时不需要如果键存在于字典中:
from copy import deepcopy
Dict1 = {'a': [1, 2, 3], 'b': [5], 'c': [5, 6, 9]}
dict2 = {'a': [4], 'b': [8, 9, 0], 'd': [10, 14, 13]}
# to store final result of dictionary
result = {}
# iterate through each dictionary in list
for dictionary in [deepcopy(Dict1), dict2]:
# iterate through key value of dictionary items
for k,v in dictionary.items():
# if key is already in result dictionary then extend new values
if k in result:
result[k].extend(v)
# else if key is not in dictionary then add key with the first value
else:
result[k] = v
print(result)
【讨论】:
keys; dict 迭代器已经生成了键。
result 时,这将修改 Dict1 中的列表,因为您没有复制这些值。
Dict1.copy() 做的浅拷贝是不够的;它创建了一个新的dict,但每个字典仍然引用相同的值。
deepcopy。
当项目不在您的列表中时,您可以使用dict.get 返回一个空列表。这允许通过循环现有的键,通过单个 dict 理解获得所需的输出。
d1 = {'a': [1, 2, 3], 'b': [5], 'c': [5, 6, 9]}
d2 = {'a': [4], 'b': [8, 9, 0], 'd': [10, 14, 13]}
output = {k: d1.get(k, []) + d2.get(k, []) for k in {*d1, *d2}}
# output: {'a': [1, 2, 3, 4], 'b': [5, 8, 9, 0], 'c': [5, 6, 9], 'd': [10, 14, 13]}
【讨论】:
你可以使用defaultdict:
final_dict = defaultdict(list)
for d in [Dict1, dict2]:
for k, v in d.items():
final_dict[k].extend(v)
结果是:
defaultdict(<type 'list'>, {'a': [1, 2, 3, 4], 'c': [5, 6, 9], 'b': [5, 8, 9, 0], 'd': [10, 14, 13]})
【讨论】:
final_dict = defaultdict(list, **deepcopy(Dict1)),这样你就可以删除你的外循环。
你可以使用itertools.groupby:
import itertools
dict1 = {'a': [1, 2, 3], 'b': [5], 'c': [5, 6, 9]}
dict2 = {'a': [4], 'b': [8, 9, 0], 'd': [10, 14, 13]}
new_l = [[a, list(b)] for a, b in itertools.groupby(sorted(list(dict1.items())+list(dict2.items()), key=lambda x:x[0]), key=lambda x:x[0])]
final_result = {a:list(itertools.chain.from_iterable([c for _, c in b])) for a, b in new_l}
输出:
{'a': [1, 2, 3, 4], 'b': [5, 8, 9, 0], 'c': [5, 6, 9], 'd': [10, 14, 13]}
【讨论】: