convert tuple of tuples to dictionary in python

Convert Tuple to a Dictionary in Python

In this tutorial, we will look at how to convert a tuple of tuples to a dictionary in Python with the help of some examples.

For instance you have a tuple containing the (name, age) tuples of some people
(("Tim", 21), ("Jim", 28)) and you want to convert it to a dictionary mapping of name: age, {"Tim": 21, "Jim": 28}

convert tuple of tuples to dictionary in python

You can use the Python built-it dict() function to convert a tuple to a dictionary. Note that for this method to work the tuples inside should be in the form (key, value).

Let’s look at an example.

# tuple of tuples
t = (("Jim", 21), ("Tim", 28))
# create dict
d = dict(t)
print(d)

Output:

{'Jim': 21, 'Tim': 28}

We get the desired dictionary from the tuple above.

What would happen if the order inside each tuple it reversed? Let’s find out.

# tuple of tuples
t = ((21, "Jim"), (28, "Tim"))
# create dict
d = dict(t)
print(d)

Output:

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

{21: 'Jim', 28: 'Tim'}

Here, the resulting dictionary is of the form age: name which is not the result we are looking for.

A more intuitive method to construct a dictionary from a tuple of tuples would be to use a dictionary comprehension. Here, we iterate over the items in the tuple and construct our dictionary according to our requirements.

Let’s the take the example from above where the out tuple contains (age, name) tuples and we want to construct a dictionary storing name: age key-value pairs.

# tuple of tuples
t = ((21, "Jim"), (28, "Tim"))
# create dict
d = {name:age for (age, name) in t}
print(d)

Output:

{'Jim': 21, 'Tim': 28}

Here, we get the desired result with name as the key and the corresponding age as the value in the dictionary.

This method is more verbose than the previous one but it’s gives us more control as to what values to use when creating a dictionary from a tuple of tuples.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top