How to Convert List to Dictionary in Python?

In Python, a list is a collection of elements that are ordered and changeable, while a dictionary is a collection of key-value pairs that are unordered, changeable, and indexed. There are several ways to convert a list to a dictionary in Python, depending on the desired key-value pairing. This article explores various methods to achieve this conversion.

Method 1: Using a Loop

One of the simplest ways to convert a list to a dictionary is by using a loop. This method allows you to specify the keys and values explicitly. Here's an example:

Output:

{0: 'apple', 1: 'banana', 2: 'cherry'}

In this example, the enumerate() function is used to iterate over the list while also keeping track of the index. Each element in the list is assigned a unique index as the key in the dictionary.

Method 2: Using zip()

Another method to convert a list to a dictionary is by using the zip() function. This function pairs elements from multiple iterables, such as lists, together. Here's an example:

Output:

{'apple': 1.0, 'banana': 0.5, 'cherry': 1.5}

In this example, the zip() function pairs each fruit with its corresponding price, creating a key-value pair in the dictionary.

Method 3: Using Dictionary Comprehension

Python also provides a concise way to convert a list to a dictionary using dictionary comprehension. This method is particularly useful when you want to perform some operation on the elements of the list. Here's an example:

Output:

{'apple': 5, 'banana': 6, 'cherry': 6}

In this example, the dictionary comprehension creates a dictionary where each fruit is a key, and the value is the length of the fruit's name.






Latest Courses