【问题标题】:Merging Python Dictionaries and adding similar value of values合并 Python 字典并添加类似的值
【发布时间】:2016-08-25 10:08:19
【问题描述】:

我有一个字典列表,例如:

[{'A': 2, 'B': u'cat'}, {'A': 1, 'B': u'dog'}, {'A': 3, 'B': u'rabbit'}, {'A': 4, 'B': u'cat'}, {'A': 4, 'B': u'dog'}, {'A': 8, 'B': u'rabbit'}]

我想把它转换成:

[{'cat':'6'},{'dog':'5'}, {'rabbit':'11'}]

我试着做这样的事情:

super_dict = collections.defaultdict(set)
        for d in ss:
            for k, v in d.iteritems():
                super_dict[k].add(v)

但它会返回:

{'A': set([2, 1, 3, 4, 4, 7]), 'B': set([u'cat', u'dog', u'rabbit'])}

【问题讨论】:

  • SO 不是代码编写服务。你应该至少付出最小的努力来自己解决这个问题。
  • @DeepSpace 对此感到抱歉。刚刚添加了我的做法。

标签: python python-2.7 dictionary


【解决方案1】:
>>> my_list = [{'A': 2, 'B': u'cat'}, {'A': 1, 'B': u'dog'}, {'A': 3, 'B': u'rabbit'}, {'A': 4, 'B': u'cat'}, {'A': 4, 'B': u'dog'}, {'A': 8, 'B': u'rabbit'}]
>>> new_dict = {}
>>> for item in my_list:
...     new_dict[item['B']] = new_dict.get(item['B'], 0) + item['A']
...
>>> new_dict
{u'dog': 5, u'rabbit': 11, u'cat': 6}

【讨论】:

    猜你喜欢
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    相关资源
    最近更新 更多