How to Convert List of Tuples to Dictionary Python?

Shape Image One

How to Convert List of Tuples to Dictionary Python?

Suppose, you have a list of tuples. Each tuple has two elements in it. Write a program to convert the Python list to dict in Python.

Let’s say you have a Python list with key-value tuples.

[(1, 'cat'), (32, 'dog'), (23, 'parrot')]

You want to convert that into the Python dictionary.

{1: 'cat', 32: 'dog', 23: 'parrot'}

Convert List of Tuples to Dict in Python

You can use the dict() method. This is the Python built-in method and you don’t need to import any package to use it.

Python code:

samp_list = [(1, 'cat'), (32, 'dog'), (23, 'parrot')]

samp_dict = dict(samp_list)

print("Dictionary: ", samp_dict)

print("Value by key: ", samp_dict[32])


Dictionary: {1: 'cat', 32: 'dog', 23: 'parrot'}
Value by key: dog

Once you convert the list into the dictionary, you can perform various operations on the Python dictionary.

Why do you need to convert the list into a dictionary?

One of the major advantages of converting a list into a dictionary is that you can easily perform the search operation by key-value pair in a Python dictionary.

It takes O(1) time to search the element in the dictionary. So if you are performing search operations on the tuple list multiple times, it is better to convert the list into the dictionary. This will save a lot of execution time and gives you performance improvement.

This simple trick is very handy when you solve competitive programming questions.

Also, read…

This is all about this simple tutorial to convert list of tuples to dictionary Python. If you have any questions, let me know in the comment section below.

Leave a Reply

Your email address will not be published. Required fields are marked *