比较指标,更新不覆盖值 [英] Comparing dicts, updating NOT overwriting values
问题描述
我不是正在寻找这样的东西:
I am not looking for something like this:
我我正在寻找这样的东西:
I am looking for something like this:
输入:
d1 = {'a': 'a', 'b': 'b'}
d2 = {'b': 'c', 'c': 'd'}
输出:
new_dict = {'a': ['a'], 'b': ['b', 'c'], 'c': ['d']}
我有以下代码有效,但我想知道是否有更有效的方法:
I have the following code which works but I am wondering if there is a more efficient method:
首先,我创建一个列表"unique_vals",其中存储了两个字典中存在的所有值. 由此,创建了一个新字典,该字典存储了两个词典中存在的所有值
First, I create a list "unique_vals", where all the values that are present in both dicts are stored. From this, a new dictionary is created which stores all the values present in both dictionaries
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
然后,对于这本新词典中未列出的两个词典中的每个值,这些值将附加到新词典中.
Then, for every value in both dictionaries that are not listed in this new dictionary, these values are appended to the new dictionary.
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
列表中的任意数量的词典.
This works with any number of dictionaries in the dicts
list.
功能:
def merge_dicts(dicts):
merged = defaultdict(list)
for d in dicts:
for key, value in d.items():
merged[key].append(value)
return merged
这篇关于比较指标,更新不覆盖值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!