追加字典以列出具有不同值的相同键

时间:2020-11-10 00:22:17

标签: python

我有一个字典列表,它们具有相同的键,而某些键的值不同。我正在尝试从列表中追加具有不同值的字典,以跟踪不同的值,并将其他键的值串联起来。例如,我要存储具有相同值的“ a”键,并串联具有相同“ a”的“ b”值:“ 1”

...

到目前为止,我尝试了以下代码,但无法识别不同的值

input list: d = [{'a': '1', 'b': '3'}, {'a': '2', 'b': '4'}, {'a': '1', 'b':'5'}]
output list: p = [{'a':'1', 'b': '35'}, {'a': '2', 'b': '4'}]

任何提示将不胜感激

1 个答案:

答案 0 :(得分:1)

使用具有a值作为其键的字典,这样您就不必遍历结果列表来查找匹配的a

temp_dict = {}
for item in d:
    if item['a'] in temp_dict:
        temp_dict[item['a']]['b'] += item['b']
    else:
        temp_dict[item['a']] = item.copy()
p = list(temp_dict.values())