w3resource logo
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]} 

Python Code Editor:

#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)

Improve this sample solution and post your code through Disqus