How to convert list of tuples to dictionary in python : Steps

In this article, you will learn how to convert a list of tuples to a dictionary in python through steps.

Syntax

You can create a tuple using the round bracket “()” and if you add more like this in a list then it is a list of tuples.

("key","value")

The syntax for the dictionary.

{ "key":"value"}

In the same way, if you add more key-value pairs to a list then it is a list of dictionaries.

Step to convert a list of tuples to the dictionary in python

Step 1: Create a sample list of tuples

In the first step, we will create a sample list of tuples that will be used while converting to the dictionary.

list_of_tuples = [("country","USA"),("capital","Washington DC"),("dial_code",1)]

Step 2: Use the following method to convert to the dictionary

Let’s know all the methods to convert a list of tuples to a dictionary in python.

Method 1: Using the dict() function.

Pass the created list of tuples to the dict() function to convert them to the dictionary.

list_of_tuples = [("country","USA"),("capital","Washington DC"),("dial_code",1)]
converted_dict = dict(list_of_tuples)
print(converted_dict)

Output

{'country': 'USA', 'capital': 'Washington DC', 'dial_code': 1}

Method 2: Tuple comprehension

In this method, we will use tuple comprehension. It is just like list comprehension. Instead of the square bracket, we will use curly braces.

list_of_tuples = [("country","USA"),("capital","Washington DC"),("dial_code",1)]
converted_dict = {t[0]:t[1] for t in list_of_tuples}
print(converted_dict)

Output

{'country': 'USA', 'capital': 'Washington DC', 'dial_code': 1}
list of tuples to dictionay in python
list of tuples to dictionary in python

Summary

In this post, you have learned how to create a tuple and dictionary. After that, we created a sample list of tuples and at last, we used two methods to convert a list of tuples to a dictionary in python. One is using the dict() function and the other by using tuple comprehension.

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link