例如:
list = [{'a':1122,'b':'qqqq'},{'a':1244,'b':'qqqq'},{'a':1233,'b':'wwww'}]
我希望连接重复的值,即两个字典在键b中包含相同的值
我想让它们像这样:
list = [{'a':2366,'b':'qqqq'},{'a':1233,'b':'wwww'}]
答案 0 :(得分:2)
我认为密钥始终为a
和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)
答案 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
键。collections.Counter
类(python2.7 +)