Convert a list of tuples to a dictionary in Python

In this article, we will discuss different ways to convert a list of tuples to a dictionary in Python.

Table Of Contents

Method 1: Using dict() constructor

Pass the list of tuples to dictionary constructor i.e. dict(). As our tuples contain only two elements, therefore the dict() will construct a dictionary by using first element in each tuple as key, and the corresponding second element as value. Let’s see an example,

# List of Tuples
listOfTuples = [('Mark', 34),
                ('John', 23),
                ('Ritu', 37),
                ('Avni', 29),
                ('John', 100),
                ('John', 102)]

# Convert a list of tuples to a dictionary using dict constructor
dictObj = dict(listOfTuples)

print(dictObj)

Output:

{'Mark': 34, 'John': 102, 'Ritu': 37, 'Avni': 29}

It converted the list of tuples to a dictionary. But this is not a perfect solution, because some data is lost here. Like, there were three different values for “John”, but in dictionary we have only one value for “John”.

Advertisements

Reason for data loss:

Basically a dictionary can have unique keys only, but in our list of tuples, we have some repeated values at the first position like “John”. Therefore, data got overwritten. If you want to handle these kind of issue, then please look into the next solution.

Method 2: Using for-loop and without data loss

Logic is as follows,

  • Create an empty dictionary.
  • Iterate over all the tuples in list one by one in a for loop. For each tuple, check if the first value of tuple exists in the dictionary or not.
    • If not, then add that as a key in dictionary, and add the corresponding second value of tuple as the value of that key.
    • If yes, then check if its value is a list or not.
      • If yes, then append the second value of tuple to that list.
      • If no, then create a list, and add the previous value to that list. Then append the second value of tuple to that list, and assign this list as value of the key.

This way we can convert a list of tuples to a dictionary without data loss. Let’s see an example,

# List of Tuples
listOfTuples = [('Mark', 34),
                ('John', 23),
                ('Ritu', 37),
                ('Avni', 29),
                ('John', 100),
                ('John', 102)]

# create empty dictionary
dictObj = {}

# convert list of tuples to a dictionary
for (firstValue, secondValue) in listOfTuples:
    if firstValue not in dictObj:
        dictObj[firstValue] = secondValue
    elif isinstance(dictObj[firstValue], list):
        dictObj[firstValue].append(secondValue)
    else:
        dictObj[firstValue] = [dictObj[firstValue]]
        dictObj[firstValue].append(secondValue)

print(dictObj)

Output:

{'Mark': 34, 'John': [23, 100, 102], 'Ritu': 37, 'Avni': 29}

In list of tuples, we had multiples for first value “John”. For all those tuples, key in dictionary is same i.e. “John”, and all the different values are stored in a list. This way no data is lost.

Method 3: Using setdefault() function

Steps are as follows,

  • Create an empty dictionary.
  • Iterate over all tuples in list, and for each tuple,
    • Pass the key(first value of tuple), and an empty list to the setdefault() function of dictionary. If that key does not exist in dictionary, then it will push that key in dictionary with empty list as default value. Then it returns that value of that key as reference.
    • Call the append() function on that reference object, and pass the second value of tuple as argument. It will append the value in list for that key.

Let’s see an example,

# List of Tuples
listOfTuples = [('Mark', 34),
                ('John', 23),
                ('Ritu', 37),
                ('Avni', 29),
                ('John', 100),
                ('John', 102)]

dictObj = {}

# Convert a list of tuples to a dictionary
for firstValue, secondValue in listOfTuples:
    dictObj.setdefault(firstValue, []).append(secondValue)

print(dictObj)

Output:

{'Mark': [34], 'John': [23, 100, 102], 'Ritu': [37], 'Avni': [29]}

We converted the list of tuples to a dictionary. For duplicated keys all the values are preserved in a list. But to prevent data loss, by default we used a list as value field for all the keys. This can cause a little performance overhead.

Summary

We learned about different ways to convert a list of tuples to a list of dictionary in Python. Thanks.

Advertisements

Thanks for reading.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top