Python - Flatten Nested Dictionary to Matrix
Last Updated : 25 Apr, 2023
Sometimes, while working with data, we can have a problem in which we need to convert a nested dictionary into Matrix, each nesting comprising the different rows in the matrix. This can have applications in many data domains. Let us discuss certain ways in which this task can be performed.
Method #1 : Using loop + zip() + map()
The combination of the above functions can be used to perform this task. In this, we use brute force to flatten the dictionary keys and then use map() and zip() to align them as rows of a matrix.
Python3 # Python3 code to demonstrate working of # Flatten Nested Dictionary to Matrix # using zip() + loop + map() # initializing dictionary test_dict = {'Gfg1': {'CS': 1, 'GATE': 2}, 'Gfg2': {'CS': 2, 'GATE': 3}, 'Gfg3': {'CS': 4, 'GATE': 5}} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # Flatten Nested Dictionary to Matrix # using zip() + loop + map() temp = list(test_dict.values()) sub = set() for ele in temp: for idx in ele: sub.add(idx) res = [] res.append(sub) for key, val in test_dict.items(): temp2 = [] for idx in sub: temp2.append(val.get(idx, 0)) res.append(temp2) res = [[idx for idx, val in test_dict.items()]] + list(map(list, zip(*res))) # printing result print("The Grouped dictionary list is : " + str(res))
Output :
The original dictionary is : {'Gfg3': {'GATE': 5, 'CS': 4}, 'Gfg1': {'GATE': 2, 'CS': 1}, 'Gfg2': {'GATE': 3, 'CS': 2}}
The Grouped dictionary list is : [['Gfg3', 'Gfg1', 'Gfg2'], ['GATE', 5, 2, 3], ['CS', 4, 1, 2]]
Time Complexity: O(n*n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2 : Using union() + list comprehension
A combination of the above methods can be used to perform this task. In this, we compute the union using union() rather than the nested loops. The result is compiled using list comprehension.
Python3 # Python3 code to demonstrate working of # Flatten Nested Dictionary to Matrix # using union() + list comprehension # initializing dictionary test_dict = {'Gfg1': {'CS': 1, 'GATE': 2}, 'Gfg2': {'CS': 2, 'GATE': 3}, 'Gfg3': {'CS': 4, 'GATE': 5}} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # Flatten Nested Dictionary to Matrix # using union() + list comprehension temp = set().union(*test_dict.values()) res = [list(test_dict.keys())] res += [[key] + [sub.get(key, 0) for sub in test_dict.values()] for key in temp] # printing result print("The Grouped dictionary list is : " + str(res))
Output :
The original dictionary is : {'Gfg3': {'GATE': 5, 'CS': 4}, 'Gfg1': {'GATE': 2, 'CS': 1}, 'Gfg2': {'GATE': 3, 'CS': 2}}
The Grouped dictionary list is : [['Gfg3', 'Gfg1', 'Gfg2'], ['GATE', 5, 2, 3], ['CS', 4, 1, 2]]
Method #3: Flatten a nested dictionary to a matrix using pandas library
Use the pandas library to flatten a nested dictionary into a matrix. It creates a DataFrame from the dictionary, fills the missing values with 0, and then converts it to a list of lists where each sublist represents a row in the matrix. The first sublist contains the keys of the inner dictionaries, and the remaining sublists contain the corresponding values.
Python3 import pandas as pd # initializing dictionary test_dict = {'Gfg1': {'CS': 1, 'GATE': 2}, 'Gfg2': {'CS': 2, 'GATE': 3}, 'Gfg3': {'CS': 4, 'GATE': 5}} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # Flatten Nested Dictionary to Matrix using pandas DataFrame df = pd.DataFrame(test_dict).T.fillna(0) # printing result res = df.reset_index().rename(columns={'index': 'Grouped'}) res = [list(res.columns)] + res.values.tolist() print("The Grouped dictionary list is : " + str(res))
OUTPUT:
The original dictionary is : {'Gfg1': {'CS': 1, 'GATE': 2}, 'Gfg2': {'CS': 2, 'GATE': 3}, 'Gfg3': {'CS': 4, 'GATE': 5}} The Grouped dictionary list is : [['Grouped', 'CS', 'GATE'], ['Gfg1', 1, 2], ['Gfg2', 2, 3], ['Gfg3', 4, 5]]
Time complexity: O(nm), where n is the number of keys in the outer dictionary and m is the number of keys in the inner dictionary with the most number of keys.
Auxiliary space: O(nm), as it creates a pandas.
Method #4: Using dictionary comprehension and itertools.chain() function
The program initializes a nested dictionary, flattens it to a matrix using dictionary comprehension and itertools.chain() function, and prints the original dictionary and the resulting matrix.
- Import the itertools module.
- Define the nested dictionary test_dict.
- Use dictionary comprehension and itertools.chain() function to flatten the nested dictionary to a matrix.
- Create a list res that consists of the headers for the table, followed by the data rows.
- Print the resulting matrix.
Python3 import itertools # initializing dictionary test_dict = {'Gfg1' : {'CS':1, 'GATE' : 2}, 'Gfg2' : {'CS':2, 'GATE' : 3}, 'Gfg3' : {'CS':4, 'GATE' : 5}} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # using dictionary comprehension and itertools.chain() function res = [['Grouped', 'CS', 'GATE']] + [[k] + list(v.values()) for k, v in test_dict.items()] # printing result print("The Grouped dictionary list is : " + str(res))
OutputThe original dictionary is : {'Gfg1': {'CS': 1, 'GATE': 2}, 'Gfg2': {'CS': 2, 'GATE': 3}, 'Gfg3': {'CS': 4, 'GATE': 5}} The Grouped dictionary list is : [['Grouped', 'CS', 'GATE'], ['Gfg1', 1, 2], ['Gfg2', 2, 3], ['Gfg3', 4, 5]]
Time complexity: O(n), where n is the number of elements in the dictionary.
Auxiliary space: O(n), where n is the number of elements in the dictionary, to store the resulting matrix.
Similar Reads
Python - Flatten Dictionary with List
Given a list and dictionary, flatten dictionary with keys and values at position of available element of key in list. Input : test_list = ["Gfg", "is", "Best", "For", "Geeks"], subs_dict = {"Gfg" : 7} Output : ['Gfg', 7, 'is', 'Best', 'For', 'Geeks'] Explanation : "Gfg" is replaced, followed by its
4 min read
Python - How to Iterate over nested dictionary ?
In this article, we will discuss how to iterate over a nested dictionary in Python. Nested dictionary means dictionary inside a dictionary and we are going to see every possible way of iterating over such a data structure. Nested dictionary in use: {'Student 1': {'Name': 'Bobby', 'Id': 1, 'Age': 20}
3 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
Python - K list Nested Dictionary Mesh
Given 2 lists, create nested mesh with constant List. Input : test_list1 = [4, 6], test_list2 = [2, 7], K = [] Output : {4: {2: [], 7: []}, 6: {2: [], 7: []}} Explanation : Nested dictionary initialized with []. Input : test_list1 = [4], test_list2 = [2], K = [1] Output : {4: {2: [1]}} Explanation :
2 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
Mapping Matrix with Dictionary-Python
The task of mapping a matrix with a dictionary involves transforming the elements of a 2D list or matrix using a dictionary's key-value pairs. Each element in the matrix corresponds to a key in the dictionary and the goal is to replace each matrix element with its corresponding dictionary value. For
4 min read
Python - Inversion in nested dictionary
Given a nested dictionary, perform inversion of keys, i.e innermost nested becomes outermost and vice-versa. Input : test_dict = {"a" : {"b" : {}}, "d" : {"e" : {}}, "f" : {"g" : {}} Output : {'b': {'a': {}}, 'e': {'d': {}}, 'g': {'f': {}} Explanation : Nested dictionaries inverted as outer dictiona
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
Python - Convert Matrix to Dictionary
The task of converting a matrix to a dictionary in Python involves transforming a 2D list or matrix into a dictionary, where each key represents a row number and the corresponding value is the row itself. For example, given a matrix li = [[5, 6, 7], [8, 3, 2], [8, 2, 1]], the goal is to convert it i
4 min read
How to Print a Dictionary in Python
Python Dictionaries are the form of data structures that allow us to store and retrieve the key-value pairs properly. While working with dictionaries, it is important to print the contents of the dictionary for analysis or debugging. Example: Using print Function [GFGTABS] Python # input dictionary
3 min read