如何在python中的dict中为相同的键添加值

时间:2015-04-24 13:07:44

标签: python dictionary data-structures

我在python中有以下键列表。

[{'country': None, 'percent': 100.0}, {'country': 'IL', 'percent': 100.0}, {'country': 'IT', 'percent': 100.0}, {'country': 'US', 'percent': 2.0202}, {'country': 'JP', 'percent': 11.1111}, {'country': 'US', 'percent': 6.9767}, {'country': 'SG', 'percent': 99.8482}, {'country': 'US', 'percent': 1.9127}, {'country': 'BR', 'percent': 95.1724}, {'country': 'IE', 'percent': 5.9041}, {'country': None, 'percent': 100.0}, {'country': None, 'percent': 100.0}]

因此,我需要为同一个国家/地区添加所有百分比,并移除None国家/地区。理想情况下,输出将是。

[{'country': 'IL', 'percent': 100.0}, {'country': 'IT', 'percent': 100.0}, {'country': 'US', 'percent': 10.9096}, {'country': 'JP', 'percent': 11.1111}, {'country': 'SG', 'percent': 99.8482}, {'country': 'BR', 'percent': 95.1724}, {'country': 'IE', 'percent': 5.9041}, ]

我尝试了以下内容。

for i, v in enumerate(response):
    for j in response[i:]:
        if v['country'] == j['country']:
            response[i]['percent'] = i['percent'] + j['percent']

但我无法成功并且正在挣扎。有人可以指出我正确的方向。

4 个答案:

答案 0 :(得分:3)

result_map = {}
for item in response:
    if item['country'] is None:
        continue
    if item['country'] not in result_map:
        result_map[item['country']] = item['percent']
    else:
        result_map[item['country']] += item['percent']

results = [
    {'country': country, 'percent': percent}
    for country, percent in result_map.items()
]

答案 1 :(得分:0)

将if的条件更改为:

if response.index(v) != response.index(j) and v['country'] == j['country']:

你要添加两倍的元素。

答案 2 :(得分:0)

使用defaultdict并过滤掉None国家/地区的解决方案:

from collections import defaultdict

data = [{'country': None, 'percent': 100.0}, {'country': 'IL', 'percent': 100.0}, {'country': 'IT', 'percent': 100.0}, {'country': 'US', 'percent': 2.0202}, {'country': 'JP', 'percent': 11.1111}, {'country': 'US', 'percent': 6.9767}, {'country': 'SG', 'percent': 99.8482}, {'country': 'US', 'percent': 1.9127}, {'country': 'BR', 'percent': 95.1724}, {'country': 'IE', 'percent': 5.9041}, {'country': None, 'percent': 100.0}, {'country': None, 'percent': 100.0}]

combined_percentages = defaultdict(float)

for country_data in data:
    country, percentage = country_data['country'], country_data['percent']

    if country:
        combined_percentages[country] += percentage

output = [{'country': country, 'percent': percentage} for country, percentage in combined_percentages.items()]

如果密钥不存在,defaultdict会创建一个值为0.0的浮点数,因此我们可以直接添加它。我认为这是解决手头问题的pythonic解决方案。

答案 3 :(得分:0)

使用itertools.groupby的解决方案:

from itertools import groupby

new_response = []
def get_country(dct):
    return dct['country']

sorted_response = sorted(response, key=get_country) # data needs to be sorted for groupby
for country, group in groupby(sorted_response, key=get_country):
    if  country is not None:
        percentages = sum(float(g['percent']) for g in group)
        new_response.append({'country': country, 'percentage': percentages})

print new_response