python - 如何将字典列表合并到字典键:list pairing?

标签 python python-2.7 list dictionary

我正在尝试将具有共享 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/

相关文章:

python单行if语句调用函数if true

python - 同时将 Pandas 函数应用于行和列以进行置信区间计算

Python - 作业 - 将任意基数转换为任意基数

java - Java中删除LinkedList中的节点

python - Python:如何获取列表列表中的内容?

python - pickle 功能

python - 使用App Engine Python处理/退回有关错误的传入电子邮件

Python urllib 添加 useragent header

python - 列表/序列的正则表达式模拟

c - 按字母顺序对链表排序