Python - Leaf and Non-Leaf Nodes Dictionary
Last Updated :
17 May, 2023
Sometimes, while working with Python, we can have a problem in which we need to work with Graph data represented in form of a Dictionary. In this, we may need to check for all the leaf and non-lead nodes. This kind of problem has direct applications in algorithms of Machine Learning. Let's discuss a way in which this task can be performed.
Input : test_dict = {'Gfg': {'is': 2, 'best': 1}}
Output : {'leaf': 2, 'non-leaf': 1}
Input : test_dict = {'Gfg': {'best': 2}}
Output : {'non-leaf': 1, 'leaf': 1}
Method 1: Using recursion + isinstance() + loop
The combination of the above functionalities can be used to solve this problem. In this, we recur for the inner nesting using recursion and check for leaves or non-leaves by value types using isinstance().
Python3
# Python3 code to demonstrate working of
# Leaf and Non-Leaf Nodes Dictionary
# Using recursion + isinstance() + loop
def hlpr_fnc(dict1, res = {'non-leaf':0, 'leaf':0}):
#res['non-leaf'] += 1
nodes = dict1.keys()
for node in nodes:
subnode = dict1[node]
if isinstance(subnode, dict):
res['non-leaf'] += 1
hlpr_fnc(subnode, res)
else:
res['leaf'] += 1
return res
# initializing dictionary
test_dict = {'a': {'b': 1, 'c': {'d': {'e': 2, 'f': 1}}, 'g': {'h': {'i': 2, 'j': 1}}}}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Leaf and Non-Leaf Nodes Dictionary
# Using recursion + isinstance() + loop
res = hlpr_fnc(test_dict)
# printing result
print("The leaf and Non-Leaf nodes : " + str(res))
Output:
The original dictionary : {'a': {'b': 1, 'c': {'d': {'e': 2, 'f': 1}}, 'g': {'h': {'i': 2, 'j': 1}}}}
The leaf and Non-Leaf nodes : {'non-leaf': 5, 'leaf': 5}
Time Complexity: O(n), where n is the number of nodes in the dictionary.
Auxiliary Space: O(n)
Method 2 : Using stack and loop
- Initialize two variables, non_leaf and leaf, to zero.
- Create an empty list stack and append the input dictionary to it.
- Use a while loop to iterate over the stack until it is empty.
- Within the loop, pop the last dictionary from the stack.
- For each key-value pair in the popped dictionary, increment non_leaf by 1 if the value is a dictionary and append it to the stack. Otherwise, increment leaf by 1.
- Return a dictionary with non-leaf and leaf as keys and their respective counts as values.
Python3
def leaf_and_nonleaf_nodes(dict1):
non_leaf = 0
leaf = 0
stack = [dict1]
while stack:
curr_dict = stack.pop()
for val in curr_dict.values():
if isinstance(val, dict):
non_leaf += 1
stack.append(val)
else:
leaf += 1
return {'non-leaf': non_leaf, 'leaf': leaf}
# initializing dictionary
test_dict = {'a': {'b': 1, 'c': {'d': {'e': 2, 'f': 1}}, 'g': {'h': {'i': 2, 'j': 1}}}}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Leaf and Non-Leaf Nodes Dictionary
# Using stack and loop
res = leaf_and_nonleaf_nodes(test_dict)
# printing result
print("The leaf and Non-Leaf nodes : " + str(res))
OutputThe original dictionary : {'a': {'b': 1, 'c': {'d': {'e': 2, 'f': 1}}, 'g': {'h': {'i': 2, 'j': 1}}}}
The leaf and Non-Leaf nodes : {'non-leaf': 5, 'leaf': 5}
Time complexity: O(N), where N is the number of nodes in the input dictionary.
Auxiliary space: O(N), where N is the maximum number of nodes stored in the stack at any given time.
Method 3 :Using a queue:
Algorithm:
- Initialize two variables non_leaf and leaf to 0.
- Create a deque and append the input dictionary to it.
- While the deque is not empty, perform the following steps:
a. Pop the leftmost element from the deque and assign it to the curr_dict variable.
b. For each value in curr_dict, do the following:
i. Check if the value is a dictionary.
ii. If the value is a dictionary, increment the non_leaf variable and append the value to the deque.
iii. If the value is not a dictionary, increment the leaf variable. - Create a dictionary with the non-leaf and leaf variables as values and return it.
Python3
from collections import deque
def leaf_and_nonleaf_nodes_queue(dict1):
non_leaf = 0
leaf = 0
queue = deque([dict1])
while queue:
curr_dict = queue.popleft()
for val in curr_dict.values():
if isinstance(val, dict):
non_leaf += 1
queue.append(val)
else:
leaf += 1
return {'non-leaf': non_leaf, 'leaf': leaf}
# initializing dictionary
test_dict = {'a': {'b': 1, 'c': {'d': {'e': 2, 'f': 1}}, 'g': {'h': {'i': 2, 'j': 1}}}}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Leaf and Non-Leaf Nodes Dictionary
# Using queue
res = leaf_and_nonleaf_nodes_queue(test_dict)
# printing result
print("The leaf and Non-Leaf nodes : " + str(res))
#This code is contributed by Jyothi pinjala
OutputThe original dictionary : {'a': {'b': 1, 'c': {'d': {'e': 2, 'f': 1}}, 'g': {'h': {'i': 2, 'j': 1}}}}
The leaf and Non-Leaf nodes : {'non-leaf': 5, 'leaf': 5}
Time Complexity: O(N), where N is the total number of elements in the input dictionary. This is because each element in the dictionary is visited only once.
Auxiliary Space: O(N), where N is the total number of elements in the input dictionary. This is because the deque used to store the dictionary elements can potentially store all N elements.
Similar Reads
Python - Filter Non-None dictionary Keys
Many times, while working with dictionaries, we wish to get keys for a non-null keys. This finds application in Machine Learning in which we have to feed data with no none values. Letâs discuss certain ways in which this task can be performed. Method #1 : Using loop In this we just run a loop for al
6 min read
Define a 3 Level Nested Dictionary in Python
In Python, dictionaries provide a versatile way to store and organize data. Nested dictionaries, in particular, allow for the creation of multi-level structures. In this article, we'll explore the process of defining a 3-level nested dictionary and demonstrate various methods to achieve this. Define
3 min read
Appending Element into a List in Python Dictionary
We are given a dictionary where the values are lists and our task is to append an element to a specific list. For example: d = {"a": [1, 2], "b": [3, 4]} and we are appending 5 to key "a" then the output will be {'a': [1, 2, 5], 'b': [3, 4]}Using append()This is the simplest and most direct way to a
3 min read
Python Print Dictionary Keys and Values
When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values.Example: Using print() MethodPythonmy_dict = {'a': 1, 'b': 2, 'c': 3} print("Keys:", l
2 min read
Three Level Nested Dictionary Python
In Python, a dictionary is a built-in data type used to store data in key-value pairs. Defined with curly braces `{}`, each pair is separated by a colon `:`. This allows for efficient representation and easy access to data, making it a versatile tool for organizing information. What is 3 Level Neste
4 min read
Get Next Key in Dictionary - Python
We are given a dictionary and need to find the next key after a given key, this can be useful when iterating over dictionaries or accessing elements in a specific order. For example, consider the dictionary: data = {"a": 1, "b": 2, "c": 3, "d": 4} if the current key is "b" then the next key should b
2 min read
Python - Add Items to Dictionary
We are given a dictionary and our task is to add a new key-value pair to it. For example, if we have the dictionary d = {"a": 1, "b": 2} and we add the key "c" with the value 3, the output will be {'a': 1, 'b': 2, 'c': 3}. This can be done using different methods like direct assignment, update(), or
2 min read
Get Python Dictionary Values as List - Python
We are given a dictionary where the values are lists and our task is to retrieve all the values as a single flattened list. For example, given the dictionary: d = {"a": [1, 2], "b": [3, 4], "c": [5]} the expected output is: [1, 2, 3, 4, 5]Using itertools.chain()itertools.chain() function efficiently
2 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 | Creating Multidimensional dictionary
Sometimes, while working with Python dictionaries we need to have nested dictionaries. But the issue is that, we have to declare before initializing a value in nested dictionary. Let's resolve this particular problem via methods discussed in this article. Method #1 : Using setdefault() This function
2 min read