Answer to Question #324251 in Python for Nuhan Habib

Question #324251

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

===================================================================


1
Expert's answer
2022-04-05T13:17:43-0400
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)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS