gpt4 book ai didi

python - 字典联合并对另一个字段求​​和

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:38 26 4
gpt4 key购买 nike

所以,我有 2 个字典,需要 sum t 字段,其中用户名重复并按用户名转换为唯一的字典,但我不知道该怎么做。谁来帮帮我?我很困惑。

{username:'unique_username', t:20}
{username:'unique_username_2', t:13}
{username:'unique_username', t:20}
{username:'unique_username_2', t:11}

我需要这样的返回

{username:'unique_username', t:40}
{username:'unique_username_2', t:33}

感谢您的关注。

最佳答案

使用可以使用collections.Counter()聚合摘要总数,然后循环该摘要以构建所需的字典:

>>> from collections import Counter

>>> maps = [
{'username': 'unique_username', 't': 20},
{'username': 'unique_username_2', 't': 13},
{'username': 'unique_username', 't': 20},
{'username': 'unique_username_2', 't': 11},
]

>>> summary = Counter()
>>> for m in maps:
summary[m['username']] += m['t']

>>> [{'username': uun, 't': total} for uun, total in summary.items()]
[{'username': 'unique_username_2', 't': 24}, {'username': 'unique_username', 't': 40}]

关于python - 字典联合并对另一个字段求​​和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43485222/

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