gpt4 book ai didi

python - 比较字典,更新而不覆盖值

转载 作者:行者123 更新时间:2023-12-02 03:32:33 25 4
gpt4 key购买 nike

不是寻找这样的东西:

How do I merge two dictionaries in a single expression?

Generic way of updating python dictionary without overwriting the subdictionaries

Python: Dictionary merge by updating but not overwriting if value exists

正在寻找这样的东西:

输入:

d1 = {'a': 'a', 'b': 'b'}
d2 = {'b': 'c', 'c': 'd'}

输出:

new_dict = {'a': ['a'], 'b': ['b', 'c'], 'c': ['d']}

我有以下代码有效,但我想知道是否有更有效的方法:

首先,我创建一个列表“unique_vals”,其中存储两个字典中存在的所有值。由此,创建一个新字典,它存储两个字典中存在的所有值

unique_vals = []
new_dict = {}
for key in list(d1.keys())+list(d2.keys()) :
unique_vals = []
try:
for val in d1[key]:
try:
for val1 in d2[key]:
if(val1 == val) and (val1 not in unique_vals):
unique_vals.append(val)
except:
continue
except:
new_dict[key] = unique_vals
new_dict[key] = unique_vals

然后,对于两个字典中未在此新字典中列出的每个值,这些值将附加到新字典中。

for key in d1.keys():
for val in d1[key]:
if val not in new_dict[key]:
new_dict[key].append(val)
for key in d2.keys():
for val in d2[key]:
if val not in new_dict[key]:
new_dict[key].append(val)

最佳答案

也许有一个defaultdict

>>> d1 = {'a': 'a', 'b': 'b'} 
>>> d2 = {'b': 'c', 'c': 'd'}
>>> from collections import defaultdict
>>>
>>> merged = defaultdict(list)
>>> dicts = [d1, d2]
>>> for d in dicts:
...: for key, value in d.items():
...: merged[key].append(value)
...:
>>> merged
defaultdict(list, {'a': ['a'], 'b': ['b', 'c'], 'c': ['d']})

这适用于 dicts 列表中任意数量的词典。

作为函数:

def merge_dicts(dicts):
merged = defaultdict(list)

for d in dicts:
for key, value in d.items():
merged[key].append(value)

return merged

关于python - 比较字典,更新而不覆盖值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58605665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com