Python词典列表的键和

时间:2011-12-21 02:42:27

标签: python list dictionary

  

可能重复:
  How to sum dict elements

我有一个字典列表如下:

[{'Name': 'A', 'amt':100},
 {'Name': 'B', 'amt':200},
 {'Name': 'A', 'amt':300},
 {'Name': 'C', 'amt':400},
 {'Name': 'C', 'amt':500},
 {'Name': 'A', 'amt':600}]

我想为每个amtname并在dict列表中得到以下结果:

 [{'Name':'A', 'amt':1000},
  {'Name':'B', 'amt':200},
  {'Name':'C', 'amt':900}]

5 个答案:

答案 0 :(得分:10)

from collections import defaultdict

c = defaultdict(int)
for d in list_of_dictionaries:
    c[d['Name']] += d['amt']

它产生c

{'A': 1000, 'C': 900, 'B': 200}

将其转换为词典列表:

[{'Name': name, 'amt': amt} for name, amt in c.items()]

结果:

[{'Name': 'A', 'amt': 1000}, {'Name': 'C', 'amt': 900}, {'Name': 'B', 'amt':200}]

答案 1 :(得分:6)

另一种可能的解决方案,这次使用itertools:

lst = [
{'Name': 'A', 'amt':100},
{'Name': 'B', 'amt':200},
{'Name': 'A', 'amt':300},
{'Name': 'C', 'amt':400},
{'Name': 'C', 'amt':500},
{'Name': 'A', 'amt':600}]

import itertools as it
keyfunc = lambda x: x['Name']

groups = it.groupby(sorted(lst, key=keyfunc), keyfunc)
[{'Name':k, 'amt':sum(x['amt'] for x in g)} for k, g in groups]

答案 2 :(得分:2)

output_dict = {}
for i in dict_list:
    if i['Name'] in output_dict:
        output_dict[i['Name']] = i['amt']
    else:
        output_dict[i['Name']] += i['amt']

会给你一个字典,其中键是名称,金额是值。如果你必须把它作为一个dicts列表:

[{'Name':key, 'amt':value} for key, value in output_dict.items()]

答案 3 :(得分:2)

示例解决方案

我不确定它是“美丽/ Pythonic够”,但它肯定很短,无需额外模块

def get_amt(name):
    return lambda x: x['amt'] if x['Name']==name else 0

names = sorted(set(map(lambda x: x['Name'], data)))
result = [{'Name':name,'amt':sum(map(get_amt(name), data))} for name in names]

证明

证明在这里:http://codepad.org/L1gcTpVK

如果您在问题中提供data,则result将与此相同:

  

[{'姓名':'A','amt':1000},{'姓名':'B','amt':200},{'姓名':'C','amt':900 }]

完全按照要求:)

答案 4 :(得分:0)

你可以这样做:

def sum(dict_list):
    result_list = []
    name_dict = {}
    for dict_item in dict_list:
        name = dict_item['Name']
        amt = dict_item['amt']
        if name_dict.has_key(name):
            pos = name_dict[name]
            result_list[pos] = {'Name':name, 'amt': (result_list[pos]['amt']+amt)}
        else:
            result_list.append(dict_item)
            name_dict[name] = len(result_list) - 1
    return result_list