【问题标题】:Segregate a list of dictionary into multiple lists将字典列表分离为多个列表
【发布时间】:2021-12-29 13:24:49
【问题描述】:

我有一个包含以下数据的字典列表

[{
  "col1":"1",
  "col2":"a"
},{
  "col1":"2",
  "col2":"b"
},{
  "col1":"3",
  "col2":"c"
}]

这里我的字典键字段是动态的(例如 col1、col2)。

我想根据关键字段分组将此字典数据分成多个列表。 我试图达到的结果应该是这样的

{
  "col1":["1","2","3"],
  "col2":["a","b","c"]
}

谁能告诉我如何用几行代码完成而不是编写多个 for 循环?

【问题讨论】:

  • 考虑使用集合模块中的defaultdict 来获取所有相同的keys 并将它们的值分组。

标签: python list dictionary


【解决方案1】:

这个解决方案怎么样?你可以试试这个collections.defaultdict() 将所有项目与相同的key 分组: 为了使其可读,最好使用loops

from collections import defaultdict

dd = defaultdict(list)

lst = [{
  "col1":"1", "col2":"a"
},{
  "col1":"2", "col2":"b"
},{
  "col1":"3", "col2":"c"
}]

for d in lst:
    #print(d)  # d is a dict
    for k, v in d.items():
        dd[k].append(v)
        
print(dd)

结果:

defaultdict(<class 'list'>, {'col1': ['1', '2', '3'], 'col2': ['a', 'b', 'c']})

【讨论】:

    猜你喜欢
    • 2011-05-04
    • 1970-01-01
    • 2020-04-23
    • 2010-12-19
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    相关资源
    最近更新 更多