Python: Print all keys of a dictionary

In this article, we will discuss different ways to print all keys of a dictionary. Then we will also cover the scenario, where we need to print all the keys of nested dictionary i.e. dictionary of dictionaries.

Print all keys of a python dictionary using for loop

In Python, the dictionary class provides a function keys(), which returns an iterable sequence of dictionary keys. Using for loop we can iterate over the sequence of keys returned by the function keys() and while iteration we can print each key. For example,

# Dictionary of string and int
word_freq = {
    'Hello' : 56,
    "at"    : 23,
    'test'  : 43,
    'This'  : 78,
    'Why'   : 11
}

# Iterate over all keys of a dictionary 
# and print them one by one
for key in word_freq.keys():
    print(key)

Output:

Hello
at
test
This
Why

Print all keys of a python dictionary by creating a list of all keys

We can also create a list of keys from the iterable sequence returned by dict.keys() function. Then we print all the items of the list (all keys of the dictionary). For example,

# Dictionary of string and int
word_freq = {
    'Hello' : 56,
    "at"    : 23,
    'test'  : 43,
    'This'  : 78,
    'Why'   : 11
}

# Get all keys of a dictionary as list
list_of_keys = list(word_freq.keys())

# Print the list containing all keys of dictionary
print(list_of_keys)

Output:

['Hello', 'at', 'test', 'This', 'Why']

Print all keys of a python dictionary by creating a list comprehension

We can also use this list comprehension to iterate over all the keys of dictionary and then print each key one by one. For example,

# Dictionary of string and int
word_freq = {
    'Hello' : 56,
    "at"    : 23,
    'test'  : 43,
    'This'  : 78,
    'Why'   : 11
}

# Iterate over all keys of dictionary 
# and print them one by one
[print(key) for key in word_freq]

Output:

Hello
at
test
This
Why

Print all keys of a nested dictionary in Python – Dictionary of dictionaries

Suppose we have a nested dictionary i.e. a kind of dictionaries which has another dictionary objects as value fields. To iterate over all the keys of a nested dictionary, we can use the recursion.

We have created a function, which yields all keys of the given dictionary. For each key-value pair in dictionary, it checks if the value is of dictionary type or not. If value is of dictionary type, then this function calls itself to access all keys of the nested dictionary and yield them too, one by one. The process goes on and on till all the nested dictionaries are covered. For example,

# A Nested dictionary i.e. dictionaty of dictionaries
students = {
            'ID 1':    {'Name': 'Shaun', 'Age': 35, 'City': 'Delhi'},
            'ID 2':    {'Name': 'Ritika', 'Age': 31, 'City': 'Mumbai'},
            'ID 3':    {'Name': 'Smriti', 'Age': 33, 'City': 'Sydney'},
            'ID 4':    {'Name': 'Jacob', 'Age': 23, 'City': {'perm': 'Tokyo', 'current': 'London'}},
            }


def all_keys(dict_obj):
    ''' This function generates all keys of
        a nested dictionary. 
    '''
    # Iterate over all keys of the dictionary
    for key , value in dict_obj.items():
        yield key
        # If value is of dictionary type then yield all keys
        # in that nested dictionary
        if isinstance(value, dict):
            for k in all_keys(value):
                yield k

# Iterate over all keys of a nested dictionary 
# and print them one by one.
for key in all_keys(students):
    print(key)

Output:

ID 1
Name
Age
City
ID 2
Name
Age
City
ID 3
Name
Age
City
ID 4
Name
Age
City
perm
current

We iterated over all keys of a nested dictionary and printed them one by one. If you want to get all keys of a nested dictionary as a list, then you can just put the values yielded by the the function all_keys() to a list. For example,

# get all keys of a nested dictionary
keys = list(all_keys(students) )

# Print the list containing all keys of the nested dictionary 
print(keys)

Output:

['ID 1', 'Name', 'Age', 'City', 'ID 2', 'Name', 'Age', 'City', 'ID 3', 'Name', 'Age', 'City', 'ID 4', 'Name', 'Age', 'City', 'perm', 'current']

Summary:

We learned ways to print all keys of a dictionary, including the nested dictionaries.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top