2012-07-18 162 views
3

我想加入字典中的关键'用户'是相同的列表,但我不知道如何。例如:Python字典列表合并

[{'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}] 

我广泛搜查没有发现堆栈溢出类似的东西,任何帮助,将不胜感激。

+1

会按字典索引的字典工作吗?也就是说,'{2:{'count2':34 ...},4:{'count2':234 ...}'等等?它更直观,可能会更容易构建 – 2012-07-18 16:08:44

回答

1

这样的事情应该工作。但有可能是更有效的方法来做到这一点(并在更少的行)...

# 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}] 
+1

输入不应该被称为'a'而不是'i'吗? – mgilson 2012-07-18 16:27:57

+1

@mgilson:是的,谢谢。我修复了它。我有点糊涂,从我的测试终端 – 2012-07-18 16:29:59

+0

复制/粘贴如果我想让列表中的结果字典具有与零相同的密钥作为默认值,该怎么办?在此先感谢 – Arkantos 2012-07-19 15:22:50

1

在阵列:

[{'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 } 

编辑:工作群体:

http://codepad.org/ObWT2Hl3

+2

只合并其中两个,而不是组合。 – 2012-07-18 16:07:19

+1

我的意思是它需要明确说明应该将哪些组加在一起;如果需要合并数百个字典,它就会失效。不过,这是解决方案的一部分。 – 2012-07-18 16:10:04

3

排序,然后你可以使用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] 
7
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() 
+3

你可以用'dd [u] .update(d)'替换d中的k,v代替d.items():dd [u] [k] = v'。 – 2012-07-18 16:28:29

+0

@LieRyan:对,完成; +1 – dugres 2012-07-18 16:33:16