How to print keys in a nested dictionary?

Question:

I’m trying to print the keys to the ‘animals’ dictionary.

life = {
    'animals': {
        'cats': ['Henri', 'Grumpy', 'Lucy'],
        'octopi': '',
        'emus': '',
        },
    'plants': '',
    'other': ''
    }

This is what I tried until now. It gives me the right result, but it also gives me an error at the end and I don’t understand why.

or k, v in life.items():
    for k1, v1 in v.items():
        print(k1)
for k, v in life.items():
    for k1, v1 in v.items():
        if 'animals':
            print(k1)

This is the result with the error I keep getting.

cats
octopi
emus
Traceback (most recent call last):
  File "<pyshell#14>", line 2, in <module>
    for k1, v1 in v.items():
AttributeError: 'str' object has no attribute 'items'
Asked By: monoctis

||

Answers:

This should work for you, nested dictionary keys can be accessed by just using dict[key0][key1][key2]…etc

for key in life["animals"]:
    print(key)
Answered By: Mike

The problem is that not all the values are dictionaries. Give this a shot:

for k in life.keys():
    if type(life[k]) is dict:
        for k1 in life[k].keys():
            print(k1)

It returns emus, cats, and octopi given your current dictionary.

Answered By: Alexandre Daly

If you want to print all keys you can do something like this:

def print_keys(dic):
    for key, value in dic.items():
        print(key)
        if isinstance(value, dict):
            print_keys(value)

But if you know what you want to print the animal keys than you can do:

print(life['animals'].keys()) # dict_keys(['cats', 'octopi', 'emus'])
# or
print(*(key for key in life['animals'])) # cats octopi emus
# or a normal loop like in the other answer.

To access an inner dictionary, it has to be of type dict. Hence we can simply use a single loop and check the type of each key element of outer dictionary and if we find a nested dictionary, we can add all the nested keys using dictionary.keys() to the main list of all the keys.
Consider the following example:

b = {1:'a',
     2:'b',
     3:{4:'A',
        5:'B'},
     6:'c'}

all_keys = list()

for key in b.keys():
   if isinstance(b[key],dict):
       all_keys.append(key)
       all_keys.append(list(b[key].keys()))
   else:
       all_keys.append(key)

The above solution would produce the following output:

Out[17]: [1, 2, 3, [4, 5], 6]
Answered By: Praveen kumar

I would also suggest this solution with indentation and plotting the type of the values as well as in case there are empty dictionaries.

def print_dictionary(dic, indent=0):
    if len(dic) == 0:
        print('t' * indent + '{}')
    for key, value in dic.items():
        print('t' * indent + str(key))
        if isinstance(value, dict):
            print_dictionary(value, indent + 1)
        else:
            print('t' * (indent + 1) + str(type(value)))
Answered By: Gianmario Spacagna
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.