w3resource
Python Exercises

Python Exercise: Converting a list of tuples into a dictionary

Python tuple: Exercise-19 with Solution

Write a Python program to convert a list of tuples into a dictionary.

Sample Solution:-

Python Code:

#create a list
l = [("x", 1), ("x", 2), ("x", 3), ("y", 1), ("y", 2), ("z", 1)]
d = {}
for a, b in l:
    d.setdefault(a, []).append(b)
print (d)

Sample Output:

{'y': [1, 2], 'z': [1], 'x': [1, 2, 3]} 

Flowchart:

Flowchart: Converting a list of tuples into a dictionary

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to reverse a tuple.
Next: Write a Python program to print a tuple with string formatting.

What is the difficulty level of this exercise?