Skip to content Skip to sidebar Skip to footer

Access Keys Inside Nested Dictionary Python

I have a JSON object like this below. Actually huge JSON file, simplified to ask this question. 'header': { 'headerAttributes': { 'pageCount': 5, 't

Solution 1:

Just loop over the lists directly. There is no need to know a length up front:

for d in json_response ['payload']:
    for inner_dict in d['firstKey']:
        print '{0[nestedKey_1]}({0]nestedKey_2})'.format(inner_dict)

The for <name> in <listobject> loop is a for each construct; no indices are generated. Instead, the loop assigns each element from the list to the target name.

I changed the name dict to d to avoid masking the built-in type. I also used string formatting to put the values from the inner dictionary into a string.

Note that I dropped using the totalCount key altogether. There is no need to look at that value here.

As for finding the length of a list, just use the len() function. Again, there is no need to use that function here, iteration directly over the list removes the need to generate indices up front.

Solution 2:

In the JSON you provided, there is only one element in the outer list of payload. But the code tries to access the first 5 elements of that list, which don't exist.

Try to avoid using direct access to values in a list like this di['key'], instead use 'di.get('key','default')`, unless you are sure it exists.

To loop through the keys-values and get the length of values under 'firstKey', use the following code:

for payload in json_response.get('payload',[]) :
    # Length of values under firstKey
    print(len(payload.get('firstKey',[])))
    # To access nested Keysfor i in payload.get('firstKey',[]) :
        for k,v in i.items() :
            print(k,':',v)

Post a Comment for "Access Keys Inside Nested Dictionary Python"