简体   繁体   English

如何使用for循环遍历列表中的这个嵌套字典

[英]How to iterate through this nested dictionary within a list using for loop

I have a list of nested dictionaries that I want to get specific values and put into a dictionary like this:我有一个嵌套字典列表,我想获取特定值并放入这样的字典中:

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'}}
      ]

I saw previous questions similar to this, but I still can't get the values such as 'axe' and 'red' .我看到了与此类似的先前问题,但我仍然无法获得'axe''red'等值。 I would like the new dict to have a 'Description' , 'Confidence' and other columns with the values from the nested dict.我希望新 dict 有一个'Description''Confidence'和其他列,其中包含来自嵌套 dict 的值。

I have tried this for loop:我试过这个for循环:

    new_dict = {}

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

I got many errors but mostly this error: TypeError: string indices must be integers我遇到了很多错误,但主要是这个错误: TypeError: string indices must be integers

Can someone please help solve how to get the values from the nested dictionary?有人可以帮助解决如何从嵌套字典中获取值吗?

You don't need to iterate through the keys in the dictionary (the inner for-loop), just access the value you want.您不需要遍历字典中的键(内部 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})

Try using this list comprehension:尝试使用此列表理解:

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

I have found a temporary solution for this.我已经找到了一个临时解决方案。 I decided to use the pandas dataframe instead.我决定改用 pandas dataframe。

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

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

so you want to write this to csv later so pandas will help you a lot for this problem using pandas you can get the desc by所以你想稍后把它写到 csv 所以 pandas 将帮助你解决这个问题,使用 pandas 你可以通过

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'}

this is how dataframe looks like ab are column of the dataframe and your nested dicts are rows of dataframe这就是 dataframe 看起来像 ab 是 dataframe 的列的方式,而您的嵌套字典是 dataframe 的行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM