Count the Key from Nested Dictionary in Python
Last Updated :
29 Jan, 2024
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': '[email protected]'}}}
result = count(nested_dict)
print("Total number of keys in the nested dictionary:", result)
OutputTotal 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)
OutputTotal 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': '[email protected]'}}}
keys_count = count_keys(nested_dict)
print("Total number of keys in the nested dictionary:", keys_count)
OutputTotal 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)
OutputTotal 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.
Similar Reads
Count all Elements in a Nested Python Dictionary Nested dictionaries are a common data structure in Python, often used to represent complex relationships and hierarchies. When working with nested dictionaries, you may encounter situations where you need to count all the elements within them. In this article, we will explore some simple and commonl
3 min read
Python - Convert Nested dictionary to Mapped Tuple The task is to convert a nested dictionary into a mapping where each key's values are transformed into tuples. This involves taking the inner dictionaries and creating tuples for each key-value pair across the nested structure. If a key appears in multiple inner dictionaries, its values should be gr
4 min read
How to Print Dictionary Keys in Python We are given a dictionary and our task is to print its keys, this can be helpful when we want to access or display only the key part of each key-value pair. For example, if we have a dictionary like this: {'gfg': 1, 'is': 2, 'best': 3} then the output will be ['gfg', 'is', 'best']. Below, are the me
2 min read
Loop Through a Nested Dictionary in Python Working with nested dictionaries in Python can be a common scenario, especially when dealing with complex data structures. Iterating through a nested dictionary efficiently is crucial for extracting and manipulating the desired information. In this article, we will explore five simple and generally
3 min read
Python - Count Dictionary Items In Python, dictionaries are one of the most widely used data structures. They allow us to store data in key-value pairs where each key maps to a value. In this article, weâll explore how to count dictionary items in Python using different methods including built-in functions and loops.Counting Total
3 min read
Python - Convert Frequency dictionary to list When we convert a frequency dictionary to a list, we are transforming the dictionary into a list of key-value or just the keys/values, depending on needs. We can convert a frequency dictionary to a list using methods such as list comprehension, loops, extend() method and itertools.chain() function.F
3 min read
Python | Count keys with particular value in dictionary Sometimes, while working with Python dictionaries, we can come across a problem in which we have a particular value, and we need to find frequency if it's occurrence. Let's discuss certain ways in which this problem can be solved. Method #1: Using loop This problem can be solved using naive method o
5 min read
Check If a Nested Key Exists in a Dictionary in Python Dictionaries are a versatile and commonly used data structure in Python, allowing developers to store and retrieve data using key-value pairs. Often, dictionaries may have nested structures, where a key points to another dictionary or a list, creating a hierarchical relationship. In such cases, it b
3 min read
Sort a Nested Dictionary by Value in Python Sorting a nested dictionary in Python involves understanding its structure, defining sorting criteria, and utilizing the `sorted()` function or `.sort()` method with a custom sorting function, often a lambda. This process is essential for organizing complex, hierarchical data efficiently. Mastery of
3 min read