【问题标题】:How to iterate through this nested dictionary within a list using for loop如何使用for循环遍历列表中的这个嵌套字典
【发布时间】:2019-10-30 02:19:47
【问题描述】:

我有一个嵌套字典列表,我想获取特定值并将其放入字典中,如下所示:

vid = [{'a':{'display':'axe', 'desc':'red'}, 'b':{'confidence':'good'}},        
       {'a':{'display':'book', 'desc':'blue'}, 'b':{'confidence':'poor'}},  
       {'a':{'display':'apple', 'desc':'green'}, 'b':{'confidence':'good'}}
      ]

之前看到过类似这样的问题,但还是无法得到'axe''red'等值。我希望新字典有一个 'Description''Confidence' 和其他列,其中包含嵌套字典中的值。

我已经尝试过这个 for 循环:

    new_dict = {}

    for x in range(len(vid)):
       for y in vid[x]['a']:
           desc = y['desc']
           new_dict['Description'] = desc

我遇到了很多错误,但主要是这个错误: TypeError: string indices must be integers

有人可以帮忙解决如何从嵌套字典中获取值吗?

【问题讨论】:

  • 请注意,这是一个字典列表:)
  • @Tserenjamts 我不认为这是重复的,因为我的问题是列表中的嵌套字典,还因为我需要它以字典形式,因为我想将它导出到 csv之后。我还希望使用 for 循环遍历嵌套的字典,因为我需要多个数据值:)

标签: python python-3.x dictionary nested


【解决方案1】:

您不需要遍历字典中的键(内部 for 循环),只需访问您想要的值。

vid = [{'a':{'display':'axe', 'desc':'red'}, 'b':{'confidence':'good'} },
       {'a':{'display':'book', 'desc':'blue'}, 'b':{'confidence':'poor'}},  
       {'a':{'display':'apple', 'desc':'green'}, 'b':{'confidence':'good'}}
      ]

new_dict = {}

list_of_dicts = []

for x in range(len(vid)):
   desc = vid[x]['a']['desc']
   list_of_dicts.append({'desc': desc})

【讨论】:

  • 我已经尝试过了,但它只返回了“desc”中的最后一项。我希望它遍历“desc”中的所有项目。知道怎么做吗?
  • 您希望字典是什么样的?
  • 我希望它具有来自每个外部字典 (0,1,2,3....) 的每个 'desc'、'confidence' 等的所有值。这可能吗?
  • 显然new_dict = {'desc': 'red', 'desc': 'blue', 'desc': 'green'}是不可能的,你想要什么?
  • 我希望最终产品是具有 3 列(描述、显示、置信度)的 csv,其中包含来自每个 0、1、2、3 的所有值.....要得到这个,我需要创建一个字典,对吗?你有什么建议?
【解决方案2】:

我已经找到了一个临时解决方案。我决定改用 pandas 数据框。

df = pd.DataFrame(columns = ['Desc'])

for x in range(len(vid)):
    desc = vid[x]['a']['desc']
    df.loc[len(df)] = [desc]

【讨论】:

    【解决方案3】:

    所以你想稍后把它写到 csv 中,这样 pandas 会帮助你解决这个问题,使用 pandas 你可以得到 desc

    import pandas as pd
    new_dict = {}
    df = pd.DataFrame(vid)
    for index, row in df.iterrows() : 
         new_dict['description'] = row['a']['desc']
    
    
                                           a                       b
              0      {'display': 'axe', 'desc': 'red'}  {'confidence': 'good'}
              1    {'display': 'book', 'desc': 'blue'}  {'confidence': 'poor'}
              2  {'display': 'apple', 'desc': 'green'}  {'confidence': 'good'}
    

    这就是数据框的外观,b 是数据框的列,而您的嵌套字典是数据框的行

    【讨论】:

      【解决方案4】:

      尝试使用此列表推导:

      d = [{'Description': i['a']['desc'], 'Confidence': i['b']['confidence']} for i in vid]
      print(d)
      

      【讨论】:

      • 不幸的是 vid 是一个列表,它显示了 AttributeError: 'list' object has no attribute 'values'
      猜你喜欢
      • 1970-01-01
      • 2022-01-13
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      相关资源
      最近更新 更多