0

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'. I would like the new dict to have a 'Description', 'Confidence' and other columns with the values from the nested dict.

I have tried this for loop:

    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

Can someone please help solve how to get the values from the nested dictionary?

3
  • Please note that it is a list of dictionaries :) Commented Oct 30, 2019 at 3:45
  • Possible duplicate of How to iterate through a nested dict? Commented Oct 30, 2019 at 5:39
  • @Tserenjamts I don't think it's a duplicate since my problem is a nested dictionary within a list, and also because I need it to be in dictionary form since I would want to export it into a csv later. I would also want it to be iterated through the nested dicts using a for loop since there are multiple data values that I need :) Commented Oct 30, 2019 at 6:39

4 Answers 4

2

You don't need to iterate through the keys in the dictionary (the inner for-loop), just access the value you want.

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})
Sign up to request clarification or add additional context in comments.

6 Comments

I tried this already but it only returned the last item from the 'desc'. I want it to iterate through all the items from 'desc'. Any idea how?
what do you want the dictionary to look like?
I want it to have all the values from each 'desc','confidence' etc from each of the outer dict (0,1,2,3....). Is that possible?
obviously new_dict = {'desc': 'red', 'desc': 'blue', 'desc': 'green'} is impossible, what do you want?
I would like the end product to be a csv with 3 columns(Description, Display, Confidence) that has all the values from each 0,1,2,3..... To get this, I would need to create a dict am I right? What do you propose?
|
1

I have found a temporary solution for this. I decided to use the pandas dataframe instead.

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

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

Comments

0

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

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 a b are column of the dataframe and your nested dicts are rows of dataframe

Comments

0

Try using this list comprehension:

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

1 Comment

Unfortunately the vid is a list and it showed me AttributeError: 'list' object has no attribute 'values'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.