![]() |
VOOZH | about |
Conversion from one data type to other is essential in various facets of programming. Be it development or competitive programming. Hence knowledge of it is quite useful and necessary. Let's discuss certain methods by which dictionary of list can be converted to the corresponding list of dictionaries.
Method #1 : Using list comprehension We can use list comprehension as the one-liner alternative to perform various naive tasks providing readability with a more concise code. We can iterate through each of dictionary element and corresponding keep constructing the list of dictionary.
The original dictionary is : {'Rash': [1, 3], 'Manjeet': [1, 4], 'Akash': [3, 4]} The converted list of dictionaries [{'Rash': 1, 'Manjeet': 1, 'Akash': 3}, {'Rash': 3, 'Manjeet': 4, 'Akash': 4}]
Time Complexity: O(n2)
Space Complexity: O(n)
Method #2 : Using zip() This approach used zip function two times, first time when we need to zip the particular index value of all lists as one and second to get all values of particular index and zip it with the corresponding keys.
The original dictionary is : {'Rash': [1, 3], 'Akash': [3, 4], 'Manjeet': [1, 4]} The converted list of dictionaries [{'Rash': 1, 'Akash': 3, 'Manjeet': 1}, {'Rash': 3, 'Akash': 4, 'Manjeet': 4}]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 3 : Using a loop to iterate through the dictionary and create a new dictionary for each key-value pair in the original dictionary.
Step-by-step approach ;
The original dictionary is : {'Rash': [1, 3], 'Manjeet': [1, 4], 'Akash': [3, 4]}
The converted list of dictionaries [{'Rash': 1, 'Manjeet': 1, 'Akash': 3}, {'Rash': 3, 'Manjeet': 4, 'Akash': 4}]Time complexity: O(n*m), where n is the number of keys in the dictionary and m is the length of the longest list value.
Auxiliary space: O(m), where m is the length of the longest list value, to store the list of dictionaries.