-2

例如:

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

我想连接两个字典的重复值在键 b 中包含相同的值

我想让它们像这样:

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

3 回答 3

2

我假设键将始终是aand b

我们将创建一个中间(默认)字典,其中的值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)
于 2012-11-09T14:01:24.353 回答
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']}
于 2012-11-09T13:50:37.323 回答
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+)
于 2012-11-09T14:19:40.600 回答