adohertyd
adohertyd

Reputation: 2689

Looping through a list nested in a dictionary

I have a python dictionary consisting of JSON results. The dictionary contains a nested dictionary, which contains a nested list which contains a nested dictionary. Still with me? Here's an example:

{'hits':{'results':[{'key1':'value1', 
                    'key2':'value2', 
                    'key3':{'sub_key':'sub_value'}},
                   {'key1':'value3',
                    'key2':'value4',
                    'key3':{'sub_key':'sub_value2'}}
                  ]}}

What I want to get from the dictionary is the sub_vale of each sub_key and store it in a different list. No matter what I try I keep getting errors.

This was my last attempt at it:

inner_list=mydict['hits']['results']#This is the list of the inner_dicts

index = 0
    for x in inner_list:
        new_dict[index] = x[u'sub_key']
        index = index + 1

print new_dict

It printed the first few results then started to return everything in the original dictionary. I can't get my head around it. If I replace the new_dict[index] line with a print statement it prints to the screen perfectly. Really need some input on this!

for x in inner_list:
    print x[u'sub_key']

Upvotes: 1

Views: 278

Answers (5)

ChipJust
ChipJust

Reputation: 1416

The index error is coming from new_dict[index] where index is larger than the size of new_dict.

List comprehension should be considered. It is generally better, but to help understand how this works in a loop. Try this instead.

new_list = []
for x in inner_list:
    new_list.append(x[u'sub_key'])

print new_list

If you want to stick with a dict, but use index for a key try this:

index = 0
new_dict = {}
    for x in inner_list:
        new_dict[index] = x[u'sub_key']
        index = index + 1

print new_dict

Ok, based on your comments below, I think this is what you wanted.

inner_list=mydict['hits']['results']#This is the list of the inner_dicts

new_dict = {}
for x in inner_list:
    new_dict[x['key2']] = x['key3']['sub_key']

print new_dict

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

>>> dic={'hits':{'results':[{'key1':'value1', 
                    'key2':'value2', 
                    'key3':{'sub_key':'sub_value'}},
                   {'key1':'value3',
                    'key2':'value4',
                    'key3':{'sub_key':'sub_value2'}}
                  ]}}
>>> inner_list=dic['hits']['results']
>>> [x[y]['sub_key'] for x in inner_list for y in x if isinstance(x[y],dict)]
['sub_value', 'sub_value2']

and if you're sure that it's key3 that always contain the inner dict, then :

>>> [x['key3']['sub_key'] for x in inner_list]
['sub_value', 'sub_value2']

without using List comprehensions:

>>> lis=[]
>>> for x in inner_list:
    for y in x:
        if isinstance(x[y],dict):
            lis.append(x[y]['sub_key'])


>>> lis
['sub_value', 'sub_value2']

Upvotes: 1

Marco de Wit
Marco de Wit

Reputation: 2804

After making some assumptions:

[e['key3']['sub_key'] for e in x['hits']['results']]

To change every instance:

for e in x['hits']['results']:
 e['key3']['sub_key'] = 1

Upvotes: 1

bogus
bogus

Reputation: 11

You forgot on level of nesting.

for x in inner_list:
    for y in x:
        if isinstance(x[y], dict) and 'sub_key' in x[y]:
            new_dict.append( x[y]['sub_key'] )

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 113940

x is a dictionary

on the first iteration of for x in ...

x={'key1':'value1', 
                'key2':'value2', 
                'key3':{'sub_key':'sub_value'}},

notice that there is no key sub_key in x but rather in x['key3']['sub_key']

Upvotes: 1

Related Questions