List of tuples to dictionary conversion in Python

PythonServer Side ProgrammingProgramming

In this article, we are going to learn how to convert the list of tuples into a dictionary. Converting a list of tuples into a dictionary is a straightforward thing.

Follow the below steps to complete the code.

  • Initialize the list with tuples.
  • Use the dict to convert given list of tuples into a dictionary.
  • Print the resultant dictionary.

Example

Let's see the code.

# initializing the list
tuples = [('Key 1', 1), ('Key 2', 2), ('Key 3', 3), ('Key 4', 4), ('Key 5', 5)]

# converting to dict
result = dict(tuples)

# printing the result
print(result)

If you run the above code, you will get the following result.

Output

{'Key 1': 1, 'Key 2': 2, 'Key 3': 3, 'Key 4': 4, 'Key 5': 5}

Let's add value as list in the resultant dictionary using setdefault() method.

Follow the below steps to complete the code.

  • Initialize the list with tuples.
  • Iterate over the list of tuples.
  • Set default value for the key and append the value.
  • Print the result.

Example

Let's see the code.

# initializing the list
tuples = [('Key 1', 1), ('Key 2', 2), ('Key 3', 3), ('Key 4', 4), ('Key 5', 5)]

# result
result = {}

# iterating over the tuples lists
for (key, value) in tuples:
   # setting the default value as list([])
   # appending the current value
   result.setdefault(key, []).append(value)

# printing the list
print(result)

If you run the above code, you will get the following result.

Output

{'Key 1': [1], 'Key 2': [2], 'Key 3': [3], 'Key 4': [4], 'Key 5': [5]}

Conclusion

If you have any queries in the article, mention them in the comment section.

raja
Published on 13-Nov-2020 17:36:46
Advertisements