【问题标题】:Python dictionary to multiple list [closed]Python字典到多个列表[关闭]
【发布时间】:2023-03-08 17:12:01
【问题描述】:

当前的问题包括将字典转换为列表。我无法将键值对的特定值拆分为我想要的结果。

我有一本像这样的字典:

dict = [ {name:aa,age:12, id:121}, {name:bb,age:13, id:122},{name:cc,age:11, id:121}, {name:dd,age:15, id:122} ]

它具有某些键和值对,并且“ID”键是其中最重要的。ID 值是重复的,因此我正在寻找该值的列表,使其看起来像这样:

121 = [
{name:aa,age:12},
{name:cc,age:11}
]

122 = [
{name:bb,age:13},
{name:dd,age:15}
]

【问题讨论】:

  • 你试过什么?您是否知道输出变量名称无效?您可能希望使用 dict 代替。并且在输入中,有多个变量名没有定义;它们应该是字符串吗?
  • 你的输出可以是一个列表字典,以'ID'作为键值,你给定的列表作为值吗?例如,answer = {121: [{name:aa, age:12}, {name:cc, age:11}]} 等?否则输出列表和id是怎么排列的?
  • 你好!我认为这完美地回答了你的问题:herehere。希望我能帮上忙!
  • @kcsquared 是的,很好
  • @VintageMind 这些似乎更多是关于将字典转换为(键,值)对。这个问题非常相似,但与this question 不完全相同;摘要是按该值对dict列表进行排序,然后是itertools.groupby()

标签: python python-3.x list dictionary


【解决方案1】:

我认为这应该可以正常工作,只需遍历子词典列表即可。

start_dict = [{'name':'aa','age':12,'id':121}, {'name':'bb','age':13,'id':122},{'name':'cc','age':11,'id':121}, {'name':'dd','age':15,'id':122}]

converted_dict = {}
for subdict in start_dict:
    if subdict['id'] not in converted_dict:
        converted_dict[subdict['id']] = [{k:v for k,v in subdict.items() if k != 'id'}]
    else:
        converted_dict[subdict['id']].append({k:v for k,v in subdict.items() if k != 'id'})
        
print(converted_dict)

{121: [{'name': 'aa', 'age': 12}, {'name': 'cc', 'age': 11}], 
 122: [{'name': 'bb', 'age': 13}, {'name': 'dd', 'age': 15}]}

【讨论】:

    【解决方案2】:
    from collections import defaultdict
    
    start_dict = [
        {'name': 'aa', 'age': 12, 'id': 121},
        {'name': 'bb', 'age': 13, 'id': 122},
        {'name': 'cc', 'age': 11, 'id': 121},
        {'name': 'dd', 'age': 15, 'id': 122},
    ]
    new_dict = defaultdict(list)
    
    for entry in start_dict:
        new_dict[entry["id"]].append(dict(name=entry["name"], age=entry["age"]))
    
    print(dict(new_dict))
    

    【讨论】:

      【解决方案3】:

      您可以使用setdefault 并使用此设置默认list 为每个keyappend 项目的值列出每个key

      start_dict = [{'name':'aa','age':12,'id':121}, {'name':'bb','age':13,'id':122},{'name':'cc','age':11,'id':121}, {'name':'dd','age':15,'id':122}]
      
      out = {}
      for sd in start_dict:
          out.setdefault(sd['id'], [])
          out[sd['id']].append({'name': sd['name'], 'age': sd['age']})
      print(out)
      

      输出:

      {
       121: [ 
             {'name': 'aa', 'age': 12}, 
             {'name': 'cc', 'age': 11}
            ], 
       122: [
             {'name': 'bb', 'age': 13}, 
             {'name': 'dd', 'age': 15}
            ]
      }
      

      【讨论】:

        猜你喜欢
        • 2016-03-15
        • 2015-07-27
        • 2015-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-10
        • 1970-01-01
        • 2020-11-24
        相关资源
        最近更新 更多