2014-04-04 88 views
1

我希望這會很容易。我有一本字典:Python:減少字典中的列表

{ 
     'key1': 'value1', 
     'key2': 'value2', 
     'key3': 'value3' 
}, 
{ 
     'key1': 'value4', 
     'key2': 'value5', 
     'key3': 'value6' 
}, 

如何減少這是以下幾點:

{ 'key1': ['value1', 'value4'], 'key2': ['value2', 'value5'], 'key3': ['value3', 'value6'] } 

非常感謝!

+2

可能重複(http://stackoverflow.com/questions/2365921/merging-python-dictionaries) – Adam

回答

3

像這樣:

from collections import defaultdict 

d1 = { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' } 
d2 = { 'key1': 'value4', 'key2': 'value5', 'key3': 'value6' } 

dout = defaultdict(list) 
for item in d1: 
    dout[item].append(d1[item]) 
for item in d2: 
    dout[item].append(d2[item]) 
print dout 
3

這個工程有兩個類型的字典使用相同的密鑰的情況下:

a = { 
    'key1': 'value1', 
    'key2': 'value2', 
    'key3': 'value3' 
} 

b = { 
'key1': 'value4', 
'key2': 'value5', 
'key3': 'value6' 
} 

c= {k: [a[k], b[k]] for k in a.keys()} 
+0

噢,那是涼爽的所有相同類型的字典。 – Scott

0

像這樣 -

vals = [{ 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' }, { 'key1': 'value4', 'key2': 'value5', 'key3': 'value6' }] 

d = {} 
for k,v in [(k,v) for item in vals for k,v in item.items()]: 
    d[k] = d[k] + [v] if d.get(k) else [v] 


#>>> d 
#{'key3': ['value3', 'value6'], 'key2': ['value2', 'value5'], 'key1': ['value1', 'value4']} 
0

轉換類型的字典列表一個帶有數值列表的字典

from itertools import chain 
result = {} 
data = [ 
    {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}, 
    {'key1': 'value4', 'key2': 'value5', 'key3': 'value6'}, 
] 

list_of_tuples = chain(*[x.items() for x in data]) 
for k, v in list_of_tuples: 
    result.setdefault(k, []).append(v) 

print(result) 

輸出:[合併Python字典]的

> python app.py 
{'key3': ['value3', 'value6'], 'key2': ['value2', 'value5'], 'key1': ['value1', 'value4']}