![]() |
VOOZH | about |
Given list of dictionaries, our task is to convert a list of dictionaries into a dictionary where each key corresponds to the index of the dictionary in the list and the value is the dictionary itself. For example: consider this list of dictionaries: li = [{"Gfg": 3, 4: 9}, {"is": 8, "Good": 2}] then the output will be {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}}.
In this method we iterate through the list using enumerate() to get both index and dictionary and then construct the final dictionary by assigning the dictionary at each index to the corresponding key.
Dictionary: {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}, 2: {'Best': 10, 'CS': 1}}
Explanation: enumerate(li) gives us index-value pairs which are directly used in dictionary comprehension to create the final result. The key is the index and the value is the corresponding dictionary from the list li.
This method simplifies the previous one by directly using a dictionary comprehension instead of creating the dictionary with a loop it does the same in a single line.
Dictionary: {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}, 2: {'Best': 10, 'CS': 1}}
This method creates a range of indices using the range() function which is then combined with the original list using the zip() function. The resulting pairs of index and dictionary are then used to construct the final dictionary using a dictionary comprehension.
The constructed dictionary: {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}, 2: {'Best': 10, 'CS': 1}}
Explanation:
This method combines map() and enumerate() to create a dictionary by mapping the indices and values from the list of dictionaries to key-value pairs.
Dictionary: {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}, 2: {'Best': 10, 'CS': 1}}
Explanation: