How To Convert List Into Dictionary In Python

In Python, lists and dictionaries are two commonly used data structures that are popular for their simplicity and functionality. But sometimes, you might need to convert the data stored in a list into a dictionary for easier access or manipulation. In this tutorial, you will learn various methods to convert a list into a dictionary using Python.

Method 1: Using a dictionary comprehension with zip()

One simple way to convert a list to a dictionary is by using a dictionary comprehension with the zip() function. The zip() function takes two iterable objects as arguments and returns a zip object, which is an iterator of tuples, where the first item in each passed iterator is paired together.

Output

{
    1: 'Apple',
    2: 'Banana',
    3: 'Cherry',
    4: 'Date'
}

Method 2: Using the dict() function

The dict() function is a built-in Python function that can be used to create a dictionary from a given iterable (e.g., a list or tuple) of key-value pairs. The syntax for the dict() function is as follows:

Here is an example showing how to use the dict() function to convert a list of tuples into a dictionary:

Output

{
    1: 'Apple',
    2: 'Banana',
    3: 'Cherry',
    4: 'Date'
}

Method 3: Using dictionary comprehension with enumerate()

If you have a list of values and you want to create a dictionary where the keys are the indices of the values, you can use the enumerate() function along with a dictionary comprehension. The enumerate() function adds a counter to an iterable and returns an enumerate object, which is an iterator containing pairs of index and value.

Output

{
    0: 'Apple',
    1: 'Banana',
    2: 'Cherry',
    3: 'Date'
}

Full Code

Output

{
    1: 'Apple',
    2: 'Banana',
    3: 'Cherry',
    4: 'Date'
}{
    1: 'Apple',
    2: 'Banana',
    3: 'Cherry',
    4: 'Date'
}{
    0: 'Apple',
    1: 'Banana',
    2: 'Cherry',
    3: 'Date'
}

Conclusion

In this tutorial, you learned how to convert a list into a dictionary using various methods like the zip() function, dict() function, and enumerate() function with dictionary comprehensions. Each method has its own advantages, so choose the one that best fits your needs when working with lists and dictionaries in Python.