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?

nam
  • 116
  • 1
  • 10
  • Please note that it is a list of dictionaries :) – nam Oct 30 '19 at 03:45
  • Possible duplicate of [How to iterate through a nested dict?](https://stackoverflow.com/questions/43752962/how-to-iterate-through-a-nested-dict) – Tserenjamts Oct 30 '19 at 05: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 :) – nam Oct 30 '19 at 06:39

4 Answers4

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})
Ollie
  • 1,641
  • 1
  • 13
  • 31
  • 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? – nam Oct 30 '19 at 03:39
  • what do you want the dictionary to look like? – Ollie Oct 30 '19 at 03:45
  • 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? – nam Oct 30 '19 at 03:47
  • obviously `new_dict = {'desc': 'red', 'desc': 'blue', 'desc': 'green'}` is impossible, what do you want? – Ollie Oct 30 '19 at 03:49
  • 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? – nam Oct 30 '19 at 03:52
  • using this: https://www.tutorialspoint.com/How-to-save-a-Python-Dictionary-to-CSV-file you would want a list of dicts, so `list_of_dicts = [{'desc': 'red'}, {'desc': 'blue'}, {'desc': 'green'}` - i've updated the answer to reflect this – Ollie Oct 30 '19 at 04:10
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]

nam
  • 116
  • 1
  • 10
0

Try using this list comprehension:

d = [{'Description': i['a']['desc'], 'Confidence': i['b']['confidence']} for i in vid]
print(d)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • Unfortunately the vid is a list and it showed me AttributeError: 'list' object has no attribute 'values' – nam Oct 30 '19 at 03:43
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

Tserenjamts
  • 579
  • 6
  • 15