Open In App

Count the Key from Nested Dictionary in Python

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, counting the occurrences of keys within a nested dictionary often requires traversing through its complex structure. In this article, we will see how to count the key from the nested dictionary in Python.

Count the Key from the Nested Dictionary in Python

Below are some ways and examples by which we can count the keys from the nested dictionary in Python:

  • Using Loop
  • Using Stack
  • Using Recursion
  • Using Collection Module

Count the Key of the Python Nested Dictionary using Loop

In this approach, we will use list comprehension to count the keys in the nested dictionary in Python. Here, we will define a function count_keys_generator and return the sum of the length of the current dictionary and the recursive call for each nested dictionary.

Python3




# Function to count keys in a nested dictionary using loop
def count(dictionary):
    return (len(dictionary)+sum(count(value)
                                for value in dictionary.values() if isinstance(value, dict)))
 
 
# Example Usage:
nested_dict = {'Dict1': {'name': 'Alice', 'age': '22', 'address': {'city': 'Wonderland'}},
               'Dict2': {'name': 'Bob', 'age': '28', 'contacts': {'email': 'bob@example.com'}}}
 
result = count(nested_dict)
print("Total number of keys in the nested dictionary:", result)


Output

Total number of keys in the nested dictionary: 10

Time Complexity: O(n), where ‘n’ is the total number of keys in the nested dictionary.
Space Complexity: O(d), where ‘d’ is the depth of the nested dictionary.

Python Count Key Nested Dictionary using Stack

In this approach, we will use a stack and iteration to traverse the nested dictionary and count the keys in Python.

Python3




# Function to count keys in a nested dictionary using a stack and iteration
def count_keys_iterative(dictionary):
    stack = [dictionary]
    count = 0
    while stack:
        current_dict = stack.pop()
        count += len(current_dict)
        stack.extend(value for value in current_dict.values()
                     if isinstance(value, dict))
    return count
 
# Example Usage:
nested_dict = {'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': 4}}}
result = count_keys_iterative(nested_dict)
print("Total number of keys in the nested dictionary:", result)


Output

Total number of keys in the nested dictionary: 6

Time Complexity: O(n), where ‘n’ is the total number of keys in the nested dictionary.
Space Complexity:O(m), where ‘m’ is the maximum number of nested dictionaries in the stack.

Count Key of Nested Dictionary using Recursion

In this example, we will recursively count the number of keys in a nested dictionary, considering nested dictionaries within lists or tuples.

Python3




def count_keys(d):
    keys = 0
 
    if isinstance(d, dict):
        for item in d.keys():
            keys += 1
            if isinstance(d[item], (list, tuple, dict)):
                keys += count_keys(d[item])
 
    elif isinstance(d, (list, tuple)):
        for item in d:
            if isinstance(item, (list, tuple, dict)):
                keys += count_keys(item)
 
    return keys
 
# Example usage
nested_dict = {'Dict1': {'name': 'Alice', 'age': '22', 'address': {'city': 'Wonderland'}},
               'Dict2': {'name': 'Bob', 'age': '28', 'contacts': {'email': 'bob@example.com'}}}
 
keys_count = count_keys(nested_dict)
print("Total number of keys in the nested dictionary:", keys_count)


Output

Total number of keys in the nested dictionary: 10

Time complexity: O(N)
Space complexity: O(N)

Count Nested Dictionary Keys using collections Module

In this approach, we use the collections module with a deque to count keys in the nested dictionary in Python. Here, we will create a deque with the root dictionary and see while the deque is not empty, pop a dictionary, increment the count by the number of keys in the current dictionary, extend the deque with values that are nested dictionaries and repeat until the deque is empty.

Python3




from collections import deque
# Function to count keys in a nested dictionary using the collections module
 
def count_keys_collections(dictionary):
    count = 0
    queue = deque([dictionary])
    while queue:
        current_dict = queue.popleft()
        count += len(current_dict)
        queue.extend(value for value in current_dict.values()
                     if isinstance(value, dict))
    return count
 
# Example Usage:
nested_dict = {'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': 4}}}
result = count_keys_collections(nested_dict)
print("Total number of keys in the nested dictionary:", result)


Output

Total number of keys in the nested dictionary: 6

Time Complexity: O(n), where ‘n’ is the total number of keys in the nested dictionary.
Space Complexity: O(m), where ‘m’ is the maximum number of nested dictionaries in the deque.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads