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)

Output:

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

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.



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program