繁体   English   中英

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

[英]How to add value for same keys in a dict in python

我在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']

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

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()
]

将if的条件更改为:

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

你要添加两倍的元素。

使用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解决方案。

使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM