Python字典列表合并
我想将字典加入一个键“user”相同的列表中,但我不知道如何加入。例如:Python字典列表合并,python,list,set,structure,dictionary,Python,List,Set,Structure,Dictionary,我想将字典加入一个键“user”相同的列表中,但我不知道如何加入。例如: [{'count2': 34, 'user': 2}, {'count4': 233, 'user': 2}, {'count2': 234, 'user': 4}, {'count4': 344, 'user': 5}] 将成为: [{'count2': 34, 'count4': 233, 'user': 2 }, {'count2': 234, 'user': 4}, {'count4': 344, 'u
[{'count2': 34, 'user': 2},
{'count4': 233, 'user': 2},
{'count2': 234, 'user': 4},
{'count4': 344, 'user': 5}]
将成为:
[{'count2': 34, 'count4': 233, 'user': 2 },
{'count2': 234, 'user': 4},
{'count4': 344, 'user': 5}]
我在stack overflow中进行了大量搜索,没有找到类似的内容,如有任何帮助,将不胜感激。在数组中:
[{'count2': 34, 'user': 2},
{'count4': 233, 'user': 2},
{'count2': 234, 'user': 4},
{'count4': 344, 'user': 5}]
这样a={'count2':34,'user':2}
和b={'count4':233,'user':2}
dict(a.items() + b.items())
将返回:
{'count2': 34, 'count4': 233, 'user': 2 }
编辑:为组工作:
您可以排序,然后使用groupby,然后将其合并
from itertools import groupby
def merge(dicts):
ret = {}
for d in dicts:
ret.update(d)
return ret
d = [...]
sorted_d = sorted(d, key=lambda x: x['user'])
grouped_d = itertools.groupby(sorted_d, key=lambda x: x['user'])
print [merge(y[1]) for y in grouped]
这样的办法应该行得通。但是可能有更有效的方法来做这件事(而且行数更少)
我的意思是,它需要明确说明哪些组应该被添加到一起;如果有数百本字典需要合并,那么它就不够了。不过,这是解决方案的一部分。按用户编制索引的词典会起作用吗?也就是说,
{2:{'count2':34…},4:{'count2':234…}
等等?它更直观,而且可能更容易构造。输入不应该被称为a
而不是i
?@mgilson:是的,谢谢。我已经解决了。我对测试终端的复制/粘贴有点糊涂。如果我想让列表中的结果字典具有与默认值?提前感谢。要做到这一点,您最好先找到“count*”键的所有唯一版本,然后在r=[{}]*len(u)
行中将它们初始化为0。您可以将替换为k,v在d中。items():dd[u][k]=v
为dd[u]。更新(d)
。
from collections import defaultdict
dl = [{'count2': 34, 'user': 2},
{'count4': 233, 'user': 2},
{'count2': 234, 'user': 4},
{'count4': 344, 'user': 5}]
print dl
dd = defaultdict(dict)
for d in dl:
dd[d['user']].update(d)
print dd.values()
# Input
a=[{'count2': 34, 'user': 2},
{'count4': 233, 'user': 2},
{'count2': 234, 'user': 4},
{'count4': 344, 'user': 5}]
# Get set of unique users
u=list(set([x['user'] for x in a]))
# Create a blank list of dictionaries for the result
r=[{}] * len(u)
# Iterate over input and add the dictionaries together
for x in a:
r[u.index(x['user'])] = dict(r[u.index(x['user'])].items() + x.items())
>>> r
[{'count2': 34, 'user': 2, 'count4': 233}, {'count2': 234, 'user': 4}, {'count4': 344, 'user': 5}]