Convert a list of tuples to a dictionary in Python

This tutorial will discuss about unique ways to convert a list of tuples to a dictionary in Python.

Table Of Contents

Suppose we have a list of tuples, in which each tuple has a Name and a number i.e.

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

Now we want to convert this list of tuples into a list. Where,

  • First element of each tuple from list, will be the key in dictionary.
  • Second element of each tuple from list, will be the value in dictionary.

If there are duplicate entried for a key, then the all values of those keys will be stored in a list. For example, above list of tuples will be converted into a dictionary like this,

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

As John was present in three tuples, so we need to construct a list as its value in the dictionary.

There are different ways to do this. Let’s dicuss them one by one.

Method 1: Using for loop

Steps are as follows,

  • Create an empty dictionary
  • Iterate over all tuples in list, and for each tuple,
    • Select first value of tuple, and check if it exists in dictionary or not,
      • If not, then add that to the dictionary as key, and use the second value of tuple as value.
      • If yes, and type of its value is list, then add second value of tuple in that list.
      • If yes, and type of its value is not list, then create an empty list,
        • Add existing value for that key in that list.
        • Add second value of tuple in that list.
        • Make that list as value of key.

It will convert a list of tuples to a dictionary, in which we can have multiple values for each key.

Let’s see the complete example,

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

dictObj = {}

# Iterate over all tuples
for (firstValue, secondValue) in listOfTuples:
    if firstValue not in dictObj:
        # If first value of tuple is not in dict
        # then add it
        dictObj[firstValue] = secondValue
    elif isinstance(dictObj[firstValue], list):
        # If key already exist and value is of list type,
        # then append value in list
        dictObj[firstValue].append(secondValue)
    else:
        # If key already exist and value is not of list type,
        # then create a list and add both the values in it
        dictObj[firstValue] = [dictObj[firstValue]]
        dictObj[firstValue].append(secondValue)

print(dictObj)

Output

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

Method 2: Using setdefault()

If you want each value of the dictionary to be a list, so that it can accommodate multiple values for a key. Then you can use the setdefault() method of dictionary.

Iterate over all tuple in list, and add them to dictionary. For each tuple,

  • Use the first value of tuple as key.
  • Use the second value as value field

If each key use the default value as list, so if the key doesn’t exist in list yet, then while adding its default value be a list. Then append the values to that list.

Let’s see the complete 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:
    # Set default value of each key as list
    # and append values in that list
    dictObj.setdefault(firstValue, []).append(secondValue)

print(dictObj)

Output

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

Summary

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

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