【问题标题】:Dict union and sum another field字典并集并求和另一个字段
【发布时间】:2017-04-19 02:23:21
【问题描述】:

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

感谢您的关注。

【问题讨论】:

  • 这些字典在列表中吗?
  • 是的,我忘了放:[{objects}, {objects} ...]

标签: python django dictionary


【解决方案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}]

【讨论】:

    猜你喜欢
    • 2018-04-16
    • 2017-08-03
    • 1970-01-01
    • 2013-06-13
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多