如何迭代字典列表以检查相同的密钥并连接

时间:2012-11-09 13:46:07

标签: python list dictionary

例如:

list  = [{'a':1122,'b':'qqqq'},{'a':1244,'b':'qqqq'},{'a':1233,'b':'wwww'}]

我希望连接重复的值,即两个字典在键b中包含相同的值

我想让它们像这样:

list = [{'a':2366,'b':'qqqq'},{'a':1233,'b':'wwww'}]

3 个答案:

答案 0 :(得分:2)

我认为密钥始终为ab

我们将创建一个中间(默认)字典,其值为b作为关键字,并总结a的值。之后,我们将数据传回列表。

import collections

data = [{'a':1122,'b':'qqqq'},{'a':1244,'b':'qqqq'},{'a':1233,'b':'wwww'}]

adder = collections.defaultdict(int)
for item in data:
    adder[item['b']] += item['a']

data = [{'a':value, 'b':key} for key, value in adder.iteritems()]
print(data)

答案 1 :(得分:1)

你想如何加起来'qqqq'& 'WWWW'?

也许这段代码会做你想做的事情:

d = [{'a':1122,'b':'qqqq'},{'a':1244,'b':'qqqq'},{'a':1233,'b':'wwww'}]
res = []

for item in d:
    for key, value in item.iteritems():
        if key not in res:
            res[key] = []
        res[key].append(value)

print res
>>> {'a': [1122, 1244, 1233], 'b': ['qqqq', 'qqqq', 'wwww']}

答案 2 :(得分:1)

这是我能提出的最通用的解决方案:

from collections import Counter,defaultdict

def sum_list_dict(lst,spec):
    d = defaultdict(list)

    #accumulate dictionaries with same "special value"
    for dd in lst:
        d[ dd[spec] ].append(dd)

    out = []
    for v in d.values():
        #Add all keys together.  Previous version excluded the special key,
        #but that really isn't necessary as we overwrite it next anyway
        new_dict = sum((Counter(x) for x in v),Counter())
        new_dict[spec] = v[0][spec]
        out.append(dict(new_dict))
    return out

lst = [{'a':1122,'b':'qqqq'},{'a':1244,'b':'qqqq'},{'a':1233,'b':'wwww'}]
print (sum_list_dict(lst,'b'))

据我所知,这个答案除了以外没有任何假设:

  • 所有词条都有spec键。
  • 输出中的dicts顺序无关紧要(可能可以补救)
  • 如果2个dicts具有相同的密钥,则必须能够将关联的值添加到一起
  • 您可以访问适当的collections.Counter类(python2.7 +)