例如:
list = [{'a':1122,'b':'qqqq'},{'a':1244,'b':'qqqq'},{'a':1233,'b':'wwww'}]
我想连接两个字典的重复值在键 b 中包含相同的值
我想让它们像这样:
list = [{'a':2366,'b':'qqqq'},{'a':1233,'b':'wwww'}]
例如:
list = [{'a':1122,'b':'qqqq'},{'a':1244,'b':'qqqq'},{'a':1233,'b':'wwww'}]
我想连接两个字典的重复值在键 b 中包含相同的值
我想让它们像这样:
list = [{'a':2366,'b':'qqqq'},{'a':1233,'b':'wwww'}]
我假设键将始终是a
and 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)
你想怎么加'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']}
这是我能想到的最通用的解决方案:
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+)