netkool
netkool

Reputation: 45

Iterate thru dict within dict

how to fetch value from the dict within dict within a array.

dict1 = {
'a': 1,
'b': 2,
'c': [{'aa': 11, 'bb': 22},{'aa': 111, 'bb': 222},{'aa': 1111, 'bb': 2222}]
}
newvalue = []
for k, v in dict1['c'].iteritems():
    newvalue.append(v[0])
    # I want to loop only 1 first time value
    for val in newvalue:
        print val

Find the first value from the dict and loop thru Desired result: First built the dict1 values Second loop thru third item "c" and print.

Got error: list' object has no attribute 'iteritems'

Upvotes: 0

Views: 61

Answers (2)

You are receiving that error because dict1['c'] is a list.

Note the square brackets surrounding the dict in:

'c': [{'aa': 11, 'bb': 22},{'aa': 111, 'bb': 222},{'aa': 1111, 'bb': 2222}]

If you are not able to change the content of the list then just call the 0th item of the list like so:

for k, v in dict1['c'][0].iteritems():
    newvalue.append(v[0])
    # I want to loop only 1 first time value
    for val in newvalue:
        print val

Upvotes: 1

Sam
Sam

Reputation: 228

for inner_dict in dict1['c']: 
    for k, v in inner_dict:
        do_something()

Upvotes: 1

Related Questions