合并Python字典并添加类似的值

时间:2016-08-25 10:08:20

标签: python python-2.7 dictionary

我有一个词典列表,如:

[{'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'])}

1 个答案:

答案 0 :(得分: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}