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 or not and then extract it’s keys using items() and then sum of find length of it using respective functions.
Python3
# 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 dictionary test_dict = { 'gfg' : { 'is' : 1 , 'best' : { 'for' : { 'Lazyroar' : 4 }}}} # Printing original dictionary print ("The original dictionary is : " + str (test_dict)) # Using recursion + items() + sum() + len() # Get total keys in dictionary res = total_keys(test_dict) # printing result print ("Number of keys in dictionary is : " + str (res)) |
The original dictionary is : {‘gfg’: {‘best’: {‘for’: {‘Lazyroar’: 4}}, ‘is’: 1}} Number of keys in dictionary is : 5
Time complexity: O(n), where n is the total number of keys in the dictionary.
Auxiliary Space: O(h), where h is the maximum depth of the nested dictionaries. This is because the recursion stack will have at most h frames at any point in time.
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
# Python3 code to demonstrate working of # Get total keys in dictionary from collections import Mapping # Utility function to perform task def 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 dictionary test_dict = { 'gfg' : { 'is' : 1 , 'best' : { 'for' : { 'Lazyroar' : 4 }}}} # Printing original dictionary print ("The original dictionary is : " + str (test_dict)) # Using yield() + recursion # Get total keys in dictionary res = sum (total_keys(test_dict)) # printing result print ("Number of keys in dictionary is : " + str (res)) |
The original dictionary is : {‘gfg’: {‘best’: {‘for’: {‘Lazyroar’: 4}}, ‘is’: 1}} Number of keys in dictionary is : 5
Method #3: Using a loop to count the number of keys
- Initialize a variable count to 0.
- Use a loop to iterate over the keys in the dictionary.
- For each key, increment the count variable by 1.
- If the value corresponding to the key is a dictionary, recursively call the function with the value as the argument and add the returned value to the count.
- Once all keys have been iterated over, return the count.
Python3
def total_keys(test_dict): count = 0 for key in test_dict: count + = 1 if isinstance (test_dict[key], dict ): count + = total_keys(test_dict[key]) return count # Initialize dictionary test_dict = { 'gfg' : { 'is' : 1 , 'best' : { 'for' : { 'Lazyroar' : 4 }}}} # Printing original dictionary print ( "The original dictionary is : " + str (test_dict)) # Using loop to count the number of keys # Get total keys in dictionary res = total_keys(test_dict) # printing result print ( "Number of keys in dictionary is : " + str (res)) |
The original dictionary is : {'gfg': {'is': 1, 'best': {'for': {'Lazyroar': 4}}}} Number of keys in dictionary is : 5
Time complexity: O(n), where n is the total number of keys in the dictionary.
Auxiliary space: O(h), where h is the maximum depth of the dictionary.