Suppose you have been given the following list of tuples.
list_1 = [("a", 1), ("b", 2), ("a", 3), ("b", 1), ("a", 2), ("c", 1)]
Write a Python program that converts this list of tuples into a dictionary and then prints the
dictionary.
[You are not allowed to use set]
Hint: Think of membership operators (in and not in).
===================================================================
Output:
{'a': [1, 3, 2], 'b': [2, 1], 'c': [1]}
===================================================================
list_1 = [("a", 1), ("b", 2), ("a", 3), ("b", 1), ("a", 2), ("c", 1)]
D = {}
for k, x in list_1:
if k in D:
D[k].append(x)
else:
D[k] = [x]
print(D)
Comments
Leave a comment