How to Convert a list of Tuples into Dictionary in Python?
|A dictionary in Python is a collection of key-value pairs. Sometimes we may have a list of tuples, where each tuple represents a key-value pair, and we may want to convert it into a dictionary. In this Python example, we will discuss how to convert a list of tuples.
Some of the topics which will be helpful for understanding the program implementation better are:
Example: Input : people = [('John', 25), ('Jane', 30), ('Mike', 40)] Output : { "John" : 25, "Jane" : 30, "Mike" : 40 }
1. Using a for
loop
We can create an empty dictionary and iterate through the list of tuples, adding each tuple to the dictionary as a key-value pair.
Now let’s implement a program to convert list of tuples to a dictionary using for
loop.
# Using a for loop people_dict = {} people = [('John', 25), ('Jane', 30), ('Mike', 40)] for person in people: people_dict[person[0]] = person[1] print(people_dict)
Output {'John': 25, 'Jane': 30, 'Mike': 40}
2. Using dict
constructor
This is a one-line implementation of the previous example. We will use list comprehension to iterate through the tuples and create a dictionary using the dict
constructor
# Using dictionary comprehension people = [('John', 25), ('Jane', 30), ('Mike', 40)] people_dict = dict((person[0], person[1]) for person in people) print(people_dict)
Output {'John': 25, 'Jane': 30, 'Mike': 40}
3. Using the zip()
function
We can use zip()
to combine the first elements of tuples into a list, and the second element of the tuples into a list, and then pass these lists to the dict()
constructor.
# Using the zip() function people = [('John', 25), ('Jane', 30), ('Mike', 40)] keys, values = zip(*people) people_dict = dict(zip(keys, values)) print(people_dict)
Output {'John': 25, 'Jane': 30, 'Mike': 40}
4. Conclusion
In this Python example, we have explored three different methods to convert a list of tuples into a dictionary in Python.
Helpful Links
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?