# Python | Get total keys in dictionary

• Last Updated : 02 Aug, 2019

Sometimes, while working with Python dictionaries, one can come in a problem in which one needs to get the exact number of keys that are present in whole of dictionaries including ones that are nested. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using recursion + items() + sum() + len()
This task can be performed using the combination of above functions. In this, we check if a nested is a dictionary of not and then extract it’s keys using items() and then sum of find length of it using respective functions.

 # Python3 code to demonstrate working of# Get total keys in dictionary# Using recursion + items() + sum() + len()  # Utility function to perform task def total_keys(test_dict):    return (0 if not isinstance(test_dict, dict)     else len(test_dict) + sum(total_keys(val) for val in test_dict.values()))  # Initialize dictionarytest_dict = { 'gfg' : { 'is'  : 1, 'best' : { 'for' : {'geeks' :4}}}}  # Printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using recursion + items() + sum() + len()# Get total keys in dictionaryres = total_keys(test_dict)  # printing result print("Number of keys in dictionary is : " + str(res))

Output :

The original dictionary is : {‘gfg’: {‘best’: {‘for’: {‘geeks’: 4}}, ‘is’: 1}}
Number of keys in dictionary is : 5

Method #2 : Using yield() + recursion
This task can also be performed using the combination of above functions. This is just another way to perform this task. The intermediate result is returned, and hence this is a more efficient method of the 2.

 # Python3 code to demonstrate working of# Get total keys in dictionaryfrom collections import Mapping  # Utility function to perform taskdef total_keys(test_dict):     for key, value in test_dict.items():         if isinstance(value, Mapping):             yield from total_keys(value)     yield len(test_dict)  # Initialize dictionarytest_dict = { 'gfg' : { 'is'  : 1, 'best' : { 'for' : {'geeks' :4}}}}  # Printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using yield() + recursion# Get total keys in dictionaryres = sum(total_keys(test_dict))  # printing result print("Number of keys in dictionary is : " + str(res))

Output :

The original dictionary is : {‘gfg’: {‘best’: {‘for’: {‘geeks’: 4}}, ‘is’: 1}}
Number of keys in dictionary is : 5

My Personal Notes arrow_drop_up