簡體   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