Open In App
Related Articles

Python – Distinct Flatten dictionaries

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Sometimes, while working with dictionaries, we can have keys which in itself is a part of very complex nestings and we wish to extract all the keys and values of particular key nesting into a separate list. This kind of problem can have applications in many domains such as web development. Lets discuss certain ways in which this task can be performed.

Distinct Flatten dictionaries Using loop + isinstance() + list comprehension 

The combination of above functions can be used to solve this problem. In this, we perform the task of flattening dictionary using checks with isinstance() and loop. At last list comprehension is used to compile the result in the form of dictionary list.
 

Python3

# Python3 code to demonstrate working of
# Distinct Flatten dictionaries
# Using loop + isinstance() + list comprehension
 
def flatten(temp_dict, temp_list):
    for key, val in temp_dict.items():
        if isinstance(val, dict):
            temp_list.append(key)
            flatten(val, temp_list)
        else:
            temp_list.extend([key, val])
    return temp_list
 
# initializing dictionary
test_dict = {'gfg' : {'is' : 4, "best" : 10}, 'is' : {'for' : { 'geeks' : 8 }}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Distinct Flatten dictionaries
# Using loop + isinstance() + list comprehension
res = [flatten(val, [key]) for key, val in test_dict.items()]
 
# printing result
print("The flattened dictionary elements : " + str(res))

                    

Output
The original dictionary is : {'is': {'for': {'geeks': 8}}, 'gfg': {'is': 4, 'best': 10}} 
The flattened dictionary elements : [['is', 'for', 'geeks', 8], ['gfg', 'is', 4, 'best', 10]]  

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Distinct Flatten dictionaries Using yield + isinstance() 

This task can also be performed using combination of above functions. In this, we use dynamic data rendering using yield to make process compact and readable.

Python3

# Python3 code to demonstrate working of
# Distinct Flatten dictionaries
# Using yield + isinstance()
 
def flatten(temp_dict):
    if isinstance(temp_dict, dict):
        for key, val in temp_dict.items():
            yield key
            yield from flatten(val)
    else:
        yield temp_dict
 
# initializing dictionary
test_dict = {'gfg' : {'is' : 4, "best" : 10}, 'is' : {'for' : { 'geeks' : 8 }}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Distinct Flatten dictionaries
# Using yield + isinstance()
res = [[key, *flatten(val)] for key, val in test_dict.items()]
 
# printing result
print("The flattened dictionary elements : " + str(res))

                    

Output
The original dictionary is : {'is': {'for': {'geeks': 8}}, 'gfg': {'is': 4, 'best': 10}} 
The flattened dictionary elements : [['is', 'for', 'geeks', 8], ['gfg', 'is', 4, 'best', 10]]  

Distinct Flatten dictionaries Using  Stack-based iterative function

we use a stack-based iterative function to flatten the dictionary. We initialize a stack with the root dictionary and an empty list. We loop until the stack is empty. For each iteration, we pop a dictionary from the stack and iterate over its key-value pairs. If the value is a dictionary, we push it onto the stack with the prefix keys. If the value is not a dictionary, we append the key-value pair to the list. We repeat the loop until the stack is empty.

Algorithm

1. Define a function named flatten_dict that takes a dictionary as input.
2. Initialize an empty list named output.
3. Iterate over each key-value pair in the dictionary.
4. If the value is a dictionary, recursively call the flatten_dict function on the nested dictionary.
5. If the value is not a dictionary, append the key-value pair as a list to the output list.
6. Return the output list.

Python3

def flatten_dict(d):
    stack = [(d, [])]
    lst = []
    while stack:
        cur, prefix = stack.pop()
        for k, v in cur.items():
            if isinstance(v, dict):
                stack.append((v, prefix + [k]))
            else:
                lst.append(prefix + [k, v])
    return lst
 
# Driver code
d = {'is': {'for': {'geeks': 8}}, 'gfg': {'is': 4, 'best': 10}}
lst = flatten_dict(d)
print(lst)

                    

Output
[['gfg', 'is', 4], ['gfg', 'best', 10], ['is', 'for', 'geeks', 8]]

Time Complexity: O(n), where n is the total number of key-value pairs in the input dictionary.

Space Complexity: O(n), where n is the total number of key-value pairs in the input dictionary. The space complexity is dominated by the stack used to perform the depth-first search of the nested dictionary.

Distinct Flatten dictionaries Using  reduce():

Algorithm :

  1. Define the flatten() function that takes a dictionary as input and flattens it into a list of distinct elements using recursion.
  2. Initialize the dictionary test_dict with some sample key-value pairs.
  3. Use reduce() function to flatten the dictionary and generate a list of distinct elements.
  4. The reduce() function iterates over the key-value pairs of the dictionary and applies the lambda function on each pair.
  5. The lambda function extracts the key and value of the current pair and calls the flatten() function on the value.
  6. The result of the flatten() function is a generator object that yields the flattened elements.
  7. Use the items() method to get the key-value pairs of the dictionary and reduce() function iterates over the key-value pairs to apply the lambda function.
  8. The final result is a list of lists where each inner list contains a distinct element from the original dictionary.

Python3

from functools import reduce
 
def flatten(temp_dict):
    if isinstance(temp_dict, dict):
        for key, val in temp_dict.items():
            yield key
            yield from flatten(val)
    else:
        yield temp_dict
 
# initializing dictionary
test_dict = {'gfg' : {'is' : 4, "best" : 10}, 'is' : {'for' : { 'geeks' : 8 }}}
 
# Distinct Flatten dictionaries
# Using reduce() + items() + lambda
res = reduce(lambda x, y: x + [[y[0], *flatten(y[1])]], test_dict.items(), [])
 
# printing result
print("The flattened dictionary elements : " + str(res))
#This code is contrinuted by Pushpa.

                    

Output
The flattened dictionary elements : [['gfg', 'is', 4, 'best', 10], ['is', 'for', 'geeks', 8]]

Time complexity:  O(n), where n is the number of elements in the dictionary. The time complexity of reduce() function is O(n), where n is the number of key-value pairs in the dictionary. Hence, the overall time complexity of the code is O(n^2).

Auxiliary Space: O(n), where n is the number of elements in the dictionary. The space complexity of reduce() function is also O(n), where n is the number of key-value pairs in the dictionary. Hence, the overall space complexity of the code is O(n^2).



Last Updated : 27 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads