Convert List to Dictionary in Python: Simple Methods to Know

Convert List To Dictionary In Python

Lists and Dictionaries are commonly used data structures in Python designed to store data sequences. Both have their own specific use cases, and it’s important to understand them before converting a list to a dictionary, also throughout this tuitorial, we will see why precisely this conversion is needed, why is it important to have a dictionary, and how to convert a list to a dictionary.

Introduction to Python List

A list in Python is a linear data structure used to store a collection of values that may be of the same or different types. A Python list is enclosed in square brackets[], and each item inside a list is separated by a comma(,).

A Python list is mutable, meaning we can change or modify its contents after its creation inside the Python program.

A Python list stores the elements in an ordered manner and we can access any element in the list directly by its index.

Example:

The below example shows how to create a list in Python and validate it using the type() function.

# Defining a Python list

ls = ['AskPython', 'CodeForGeek', 'LinuxforDevices']

# Printing the results
print(ls)

# Validating the type of 'ls'
print(type(ls))

Output:

['AskPython', 'CodeForGeek', 'LinuxforDevices']
<class 'list'>

Here we can see that type() returns an object that represents the ‘list’ class, so the ‘ls’ variable is considered a list.

We have a dedicated tutorial on Python List, consider reading it if you want to learn more about the lists.

Introduction to Python Dictionary

A dictionary in Python is a special type of data structure used to store data in a key-value pair format. A single dictionary has two main components: the key and the value, where the key must be a single entity, but the value can be a multi-valued entity such as a list, tuple, etc.

The key and its value are separated by a colon (:) and a comma (,) separates each item (a key-value pair). A dictionary is enclosed in curly brackets {}, and just like lists, dictionaries are also a mutable data structure. A dictionary without any key-value pairs is called an empty dictionary.

A Python dictionary stores the elements in an unordered manner that can access directly by its key.

Example:

The below example shows how to create a dictionary in Python and validate it using the type() function.

# Defining a Python dictionary
ds = {'AskPython': 'Python', 'CodeForGeek': 'JavaScript', 'LinuxforDevices': 'Unix/Linux'}

# Printing the results
print(ds)

# Validating the type of 'ds'
print(type(ds))

Output:

{'AskPython': 'Python', 'CodeForGeek': 'JavaScript', 'LinuxforDevices': 'Unix/Linux'}
<class 'dict'>

Here we can see that type() returns an object that represents the ‘dict’ class, so the here ‘ds’ variable is considered a dictionary.

Why Convert a List into a Dictionary?

Converting a list into a dictionary can be helpful in many situations where you need to get data in a more precise way. There can be many reasons for this but some that you often see are given below.

  1. Dictionary uses key-value pairs to store data, it is more convenient than a list when data needs to be accessed from a large set of data.
  2. The keys associated with the values are unique so there can be no place of doubt that the data selected is correct.
  3. Data manipulation in the dictionary is easier than a list, that is another reason why a list should convert into a dictionary.
  4. A dictionary is unordered, sometimes we don’t want to maintain order like we have to do in the list.

We have two effective methods to convert a list to a dictionary in Python. Using the zip() function and using dictionary comprehension. Let’s look at each of them so that you can use them as per your requirement.

Convert a Python List to a Dictionary using dictionary comprehension

A list can be converted into a dictionary by using dictionary comprehension which provides an efficient way to create a dictionary by iterating over a list. We can use it with a list to make the corresponding key: value inside the curly brackets {} where each list element becomes a key of the dictionary and the value for each key can be generated accordingly using expressions or functions. 

Example:

Let’s see an example that uses dictionary comprehension to convert a list to a Python dictionary. 

# Defining a list
ls = ['A', 'S', 'K', 'P', 'Y', 'T', 'H', 'O', 'N']

# Using dictionary comprehension to convert the list to a dictionary
ds = {item: ord(item) for item in ls}

# Printing the results
print("Given list: ", ls)
print("Generated dictionary: ", ds)

# Validating the type of 'ds'
print(type(ds))

In the above code, we have used the Python ord() function to get the ASCII value of each item inside the list and then assigned the ASCII value returned by the ord() function to the corresponding key of the dictionary as its value. This way we end up generating a key-value pair for each item inside the list where each key is a list item itself and the value is its ASCII value, and successfully converted the list into dictionary.

Output:

Given list:  ['A', 'S', 'K', 'P', 'Y', 'T', 'H', 'O', 'N']
Generated dictionary:  {'A': 65, 'S': 83, 'K': 75, 'P': 80, 'Y': 89, 'T': 84, 'H': 72, 'O': 79, 'N': 78}

Convert a Python List to a Dictionary using the zip() function

We can convert lists using the zip() function into a single dictionary. The zip() function can take two or more lists as arguments and returns an iterator that contains tuples having the i-th element from each list. Then we can further convert those tuples to a dictionary using the dict() method.

Example:

Let’s now see an example that uses the Python zip() function to convert a list to a Python dictionary. 

list1 = ['AskPython', 'CodeForGeek', 'LinuxforDevices']
list2 = ['Python', 'JavaScript', 'Unix/Linux']
ds = dict(zip(list1, list2))

# Printing the results
print(ds) 

# Validating the type of 'ds'
print(type(ds))

Here we have used the zip() function and passed two lists as an argument, then we used the dist() method to convert iterator returns by the zip() function into a dictionary having the keys and values. The dictionary keys are the elements of the first list and dictionary values are the elements of the second list.

Output:

{'AskPython': 'Python', 'CodeForGeek': 'JavaScript', 'LinuxforDevices': 'Unix/Linux'}
<class 'dict'>

Conclusion

Python lists and dictionaries are two crucial data structures in Python used to store data. We can convert the given list into a dictionary if we have to access the element by using its keys not by its order. There are different ways to convert a Python list into a dictionary which we have discussed in this tuitorial. You can choose one according to your need. As a suggestion, using the zip() function is better if you have two or more lists to convert into a single dictionary otherwise using a dictionary comprehension is also a good approach.

Reference

https://docs.python.org/3/tutorial/datastructures.html