我当前的列表:
my_list = [
{'id': 1, 'val': [6]},
{'id': 2, 'val': [7]},
{'id': 3, 'val': [8]},
{'id': 2, 'val': [9]},
{'id': 1, 'val': [10]},
]
期望的输出:
my_list = [
{'id': 1, 'val': [6, 10]},
{'id': 2, 'val': [7, 9]},
{'id': 3, 'val': [8]},
]
到目前为止我尝试了什么:
my_new_list = []
id_set = set()
for d in my_list:
if d['id'] not in id_set:
id_set.add(d['id'])
temp = {'id': d['id'], 'val': d['val']}
my_new_list.append(temp)
else:
# loop over the new list and find the dict which already have d['id'] and update by appending value
# but this is not efficient
任何其他更有效的方法或者可能是我不知道的一些内置函数。
PS:顺序很重要!
最佳答案
.setdefault()
是你的 friend :
(我们应该使用 collections.OrderedDict
来记住键首次插入的顺序。)
>>> import collections
>>> result = collections.OrderedDict()
>>> for d in my_list:
... result.setdefault(d["id"], []).extend(d["val"])
>>> lst = []
>>> for k, v in result.items():
... lst.append({"id": k, "val": v})
关于python - 合并具有列表 init 的字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37109624/