简体   繁体   中英

How to add value for same keys in a dict in python

I have the following list of keys in 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}]

So I need to add all the percentages for the same country and remove country that is None . Ideally the output would be.

[{'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}, ]

I tried the following.

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

But I could not succeed and am struggling. Could someone please point me out in the right direction.

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

Change the condition of the if to:

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

You're addding twice the elements.

A solution using defaultdict and filtering out the None country:

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

The defaultdict creates a float with value 0.0 if the key doesn't exist so we can directly add to it. I think this is a pythonic solution to the problem at hand.

A solution using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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