gpt4 book ai didi

python - 字典中特定键的总和值

转载 作者:太空宇宙 更新时间:2023-11-04 09:23:13 26 4
gpt4 key购买 nike

我有一个看起来像这样的字典列表:

source_dict = [{'ppl': 10, 'items': 15, 'airport': 'lax', 'city': 'Los Angeles', 'timestamp': 1, 'region': 'North America', 'country': 'United States'},
{'ppl': 20, 'items': 32, 'airport': 'JFK', 'city': 'New York', 'timestamp': 2, 'region': 'North America', 'country': 'United States'},
{'ppl': 50, 'items': 20, 'airport': 'ABC', 'city': 'London', 'timestamp': 1, 'region': 'Europe', 'country': 'United Kingdom'}... ]

#Gets the list of countries in the dict
countries = list(set(stats['country'] for stats in source_dict))

我知道我可以使用一个集合:

    counter = collections.Counter()

for d in source_dict:
counter.update(d)

但是,想要按国家/地区分组并仅获取某些键的总数而不是所有键的总数。

所以结果应该是

{'Country': 'United States', 'p95': 30, 'items':37},
{'Country': 'England', 'ppl': 50, 'items':20},...

我不确定如何将多个键合并到一个计数器中。产生那个结果

最佳答案

这是一种使用 collections.defaultdictcollections.Counter 的方法。

例如:

from collections import defaultdict, Counter

source_dict = [{'ppl': 10, 'items': 15, 'airport': 'lax', 'city': 'Los Angeles', 'timestamp': 1, 'region': 'North America', 'country': 'United States'},
{'ppl': 20, 'items': 32, 'airport': 'JFK', 'city': 'New York', 'timestamp': 2, 'region': 'North America', 'country': 'United States'},
{'ppl': 50, 'items': 20, 'airport': 'ABC', 'city': 'London', 'timestamp': 1, 'region': 'Europe', 'country': 'United Kingdom'} ]

result = defaultdict(Counter)
for stats in source_dict:
result[stats['country']].update(Counter({'ppl': stats['ppl'], "items": stats['items']}))

#result = [{'Country': k, **v} for k, v in result.items()] #Required output
print(result)

输出:

defaultdict(<class 'collections.Counter'>,
{'United Kingdom': Counter({'ppl': 50, 'items': 20}),
'United States': Counter({'items': 47, 'ppl': 30})})

关于python - 字典中特定键的总和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59046344/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com