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': 'bob@example.com'}}}
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': 'bob@example.com'}}}
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
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.Pythona = { "a": {"x": 1, "y": 2}, "b": {"x": 3, "y": 4}, } # Convert nested dictionary to a list of li
3 min read
Python Get All Values from Nested Dictionary
In this article, we will learn how we can Get all Values from Nested Dictionary in Python Programming. A nested Dictionary in Python is a dictionary that contains another dictionary as its values. Using this, we can create a nested structure where each of the key-value pairs is in the outer dictiona
5 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
Python - Summation of Custom nested keys in Dictionary
Given a dictionary with keys as nested dictionaries, find the sum of values of certain custom keys inside the nested dictionary. Input : test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12}, 'is' : {1 : 9, 5: 7, 9: 2}, 'best' : {1 : 3, 5: 4, 9: 14}}, sum_key = [1] Output : 18 Explanation : 6 + 9 + 3 = 18, only
10 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
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'.Usi
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
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