2016-11-21 69 views
2

我试图将带有共享键的字典列表合并到一个键中:列表配对列表包含所有值。底部的代码是这样做的,但它非常难看。我依稀记得能够在字典清单上使用reduce来完成这个任务,但是我不知所措。如何将字典列表合并为字典键:列表配对?

1 dictionaries = [{key.split(',')[0]:key.split(',')[1]} for key in open('test.data').read().splitlines()] 
    2 print dictionaries 
    3 new_dict = {} 
    4 for line in open('test.data').read().splitlines():                     
    5  key, value = line.split(',')[0], line.split(',')[1] 
    6  if not key in new_dict: 
    7   new_dict[key] = [] 
    8  new_dict[key].append(value) 
    9 print new_dict 

输出:

[{'abc': ' a'}, {'abc': ' b'}, {'cde': ' c'}, {'cde': ' d'}] 
{'cde': [' c', ' d'], 'abc': [' a', ' b']} 

test.data包含:

abc, a 
abc, b 
cde, c 
cde, d 
+0

代码。 – wwii

+2

@wwii:工作的代码是*很好*。美丽的代码令人高兴 –

回答

5

for循环可以用collections.defaultdict为简化:即工作是美丽的

from collections import defaultdict 

new_dict = defaultdict(list) 

for line in open('test.data').readlines(): # `.readlines()` will work same as 
              # `.read().splitlines()` 
    key, value = line.split(', ') # <-- unwrapped and automatically assigned 
    new_dict[key].append(value)