2016-11-21 102 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)