Converting a list to a dictionary is a common task in Python programming. In this blog post, we’ll explore different code examples that demonstrate how to convert a list to a dictionary efficiently.
Example 1:
fruits = ['apple', 'banana', 'orange', 'kiwi'] fruits_dict = {index: fruit for index, fruit in enumerate(fruits)} print(fruits_dict)
Output: {0: ‘apple’, 1: ‘banana’, 2: ‘orange’, 3: ‘kiwi’}
Example 2:
numbers = [1, 2, 3, 4, 5] numbers_dict = {value: value ** 2 for value in numbers} print(numbers_dict)
Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}