![]() |
VOOZH | about |
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.
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.
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.
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.
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(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.