我正在尝试将具有共享 key 的字典列表合并到 key:list 配对中,其中列表包含所有值。底部的代码可以做到这一点,但它非常难看。我依稀记得能够在字典列表上使用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']}
测试数据包含:
abc, a
abc, b
cde, c
cde, d
最佳答案
您的 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)
关于python - 如何将字典列表合并到字典键:list pairing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40729553/