[英]how to union list of dicts python
I have the list of dicts like: 我有像这样的字典列表:
list_of_dict = [{},
{'a': 2},
{'a': 3},
{'b': 2, 'c': 4}]
and want to create a new list like: 并想要创建一个新列表,例如:
new_list = [{'a': 2, 'b': 2, 'c':4},
{'a': 3}]
where dicts are combined if they don't have keys intersection or values of intersected keys are the same. 如果字典没有键相交或相交的键的值相同,则将其合并。
I take first pair, check intersected keys (and values if intersection is) then delete this pair and replace with new dict. 我选择第一对,检查相交的键(如果相交,则检查值),然后删除该对并替换为新的dict。 When should I stop?
我什么时候应该停下来?
list_of_dict = [{},
{'a': 2},
{'a': 3},
{'b': 2, 'c': 4}]
keys_a = set(list_of_dict[0].keys())
keys_b = set(list_of_dict[1].keys())
intersection = keys_a & keys_b
while ??:
if not intersection or //check intersected is equal//:
list_of_dict[0].update(list_of_dict[1])
list_of_dict.pop(1)
print list_of_dict
Solution for 2.7 2.7解决方案
import copy
dcts = []
buffer = {}
for i in list_of_dict:
if not i or any(j in buffer for j in i.keys()):
buffer = i
else:
new_ = copy.deepcopy(i)
new_.update(buffer)
buffer = copy.deepcopy(new_)
dcts.append(buffer)
print dcts
Here is a solution, checks if any keys in the current dictionary exist in the buffer, and if so creates a new list entry, otherwise it merges the current dictionary with the buffer: 这是一个解决方案,检查缓冲区中是否存在当前字典中的任何键,如果存在,则创建一个新的列表条目,否则它将当前字典与缓冲区合并:
dcts = []
buffer = {}
for i in list_of_dict:
if any(j in buffer for j in i.keys()):
dcts.append(buffer)
buffer = i
else:
buffer = {**i, **buffer}
dcts.append(buffer)
print(dcts)
Output: 输出:
[{'a': 2}, {'b': 2, 'c': 4, 'a': 3}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.