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
Python - Sorted Nested Keys in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the keys of nested dictionaries and render them in sorted order. This kind of application can occur in domains in which we work with data. Lets discuss certain ways in which this task can be perf
4 min read
Convert Nested Dictionary to List in Python
In this article, weâll explore several methods to Convert Nested Dictionaries to a List in Python. List comprehension is the fastest and most concise way to convert a nested dictionary into a list. [GFGTABS] Python a = { "a": {"x": 1, "y": 2}, "b": {"x
3 min read
Create Dictionary from the List-Python
The task of creating a dictionary from a list in Python involves mapping each element to a uniquely generated key, enabling structured data storage and quick lookups. For example, given a = ["gfg", "is", "best"] and prefix k = "def_key_", the goal is to generate {'def_key_gfg': 'gfg', 'def_key_is':
3 min read
Python - Remove K valued key from Nested Dictionary
We are given a nested dictionary we need to remove K valued key. For example, we are given a nested dictionary d = { "a": 1, "b": {"c": 2,"d": {"e": 3,"f": 1},"g": 1},"h": [1, {"i": 1, "j": 4}]} we need to remove K valued key ( in our case we took k value as 1 ) from it so that the output should be
3 min read
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
Python | Sum values for each key in nested dictionary
Given a nested dictionary and we have to find sum of particular value in that nested dictionary. This is basically useful in cases where we are given a JSON object or we have scraped a particular page and we want to sum the value of a particular attribute in objects. Code #1: Find sum of sharpness v
2 min read
Python | Safe access nested dictionary keys
Sometimes, while working with Python we can have a problem in which we need to get the 2nd degree key of dictionary i.e the nested key. This type of problem is common in case of web development, especially with the advent of NoSQL databases. Let's discuss certain ways to safely get the nested availa
3 min read
Get the First Key in Dictionary - Python
We are given a dictionary and our task is to find the first key in the dictionary. Since dictionaries in Python 3.7+ maintain insertion order, the first key is the one that was added first to the dictionary. For example, if we have the dictionary {'a': 10, 'b': 20, 'c': 30}, the first key is 'a'. Us
2 min read