[英]Python: Update the dict[key] values list only with values not already in list
I am trying to add/append test_dict2
to test_dict
, according to the below rules:我正在尝试根据以下规则将test_dict2
添加/附加到test_dict
:
test_dict2
dictionary key already exists in test_dict
, update test_dict[key]
with only new values from test_dict2[key]
如果test_dict2
字典键已存在于test_dict
中,则仅使用来自 test_dict2[key] 的新值更新test_dict[key]
test_dict2[key]
test_dict
, add the key and value.如果test_dict
中不存在字典键,请添加键和值。Example:例子:
test_dict = {'s': [1, 2], 't': 2}
test_dict2 = {'s': [1, 2, 3, 'yoyoyo'], 't': 2, 'u': [3, 4]}
After my intended update, test_dict should look like this:在我打算更新之后, test_dict 应该是这样的:
test_dict = {'s': [1, 2, 3, 'yoyoyo'], 't': [2], 'u': [3, 4]}
I have working code, but it seems so inefficient:我有工作代码,但似乎效率很低:
def convert_values_to_list(value):
if isinstance(value, list) == False:
value = [value]
return value
for key, values in test_dict2.items():
values = convert_values_to_list(values)
print(key)
print(values)
if key not in test_dict:
test_dict[key] = values
else:
test_dict[key] = convert_values_to_list(test_dict[key])
for value in values:
if value not in test_dict[key]:
test_dict[key].append(value)
Try this.尝试这个。
def unpack_values(data):
for datum in data:
if isinstance(datum, list):
for x in datum:
yield x
else:
yield datum
all_keys=set(test_dict.keys())
all_keys.update(test_dict2.keys())
for key in all_keys:
values=[test_dict.get(key,[]), test_dict2.get(key,[])]
test_dict[key]=list(set(unpack_values(values)))
You could try using a library to help with this, I found deepmerge
, which also supports custom strategies, so you could make this a one-liner in theory:您可以尝试使用库来帮助解决此问题,我发现deepmerge
也支持自定义策略,因此您可以在理论上使其成为单线:
>>> from deepmerge import always_merger
>>> a = {'s': [1, 2], 't': 2}
>>> b = {'s': [1, 2, 3, 'yoyoyo'], 't': 2, 'u': [3, 4]}
and then接着
>>> always_merger.merge(a, b) # a was modified in place
{'s': [1, 2, 1, 2, 3, 'yoyoyo'], 't': 2, 'u': [3, 4]}
>>> {k: list(set(v)) if isinstance(v, list) else [v] for k, v in a.iteritems()}
{'s': [1, 2, 3, 'yoyoyo'], 't': [2], 'u': [3, 4]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.