Dict联合并加上另一个字段

时间:2017-04-19 02:23:21

标签: python django dictionary

所以,我有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}

感谢您的关注。

1 个答案:

答案 0 :(得分:1)

使用可以使用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}]