如何将字典列表合并到字典键中:列表配对?

时间:2016-11-21 21:16:43

标签: python python-2.7 list dictionary

我正在尝试将带有共享密钥的字典列表合并到一个密钥中:列表配对,其中列表包含所有值。底部代码做到了,但它非常难看。我依稀记得能够在词典列表中使用reduce来实现这一点,但我不知所措。

num

输出:

  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

test.data包含:

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

1 个答案:

答案 0 :(得分: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)