繁体   English   中英

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

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

我有一个嵌套字典列表,我想获取特定值并放入这样的字典中:

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'等值。 我希望新 dict 有一个'Description''Confidence'和其他列,其中包含来自嵌套 dict 的值。

我试过这个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

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

您不需要遍历字典中的键(内部 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})

尝试使用此列表理解:

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

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

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

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

所以你想稍后把它写到 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'}

这就是 dataframe 看起来像 ab 是 dataframe 的列的方式,而您的嵌套字典是 dataframe 的行

暂无
暂无

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

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