I am not寻找这样的东西:
如何将两个字典合并到一个表达式中? https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression
更新Python字典而不覆盖子字典的通用方法 https://stackoverflow.com/questions/22093793/generic-way-of-updating-python-dictionary-without-overwriting-the-subdictionarie?lq=1
Python:如果值存在,则通过更新但不覆盖来合并字典 https://stackoverflow.com/questions/6354436/python-dictionary-merge-by-updating-but-not-overwriting-if-value-exists
I am寻找这样的东西:
input:
d1 = {'a': 'a', 'b': 'b'}
d2 = {'b': 'c', 'c': 'd'}
output:
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)