Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have the list of tuples.

list = [("a", 1), ("b", 2), ("a", 3), ("b", 1), ("a", 2), ("c", 1)]

I want to convert this list of tuples into the dictionary.

Output:

{'a': [1, 3, 2], 'b': [2, 1], 'c': [1]}

My code:

list_a = [("a", 1), ("b", 2), ("a", 3), ("b", 1), ("a", 2), ("c", 1)]

new_dict = {}

value = []

for i in range(len(list_a)):

    key = list_a[i][0]

    

    value.append(list_a[i][1])

    

    new_dict[key] = value

print(new_dict)

However, my output is as shown below:

{'a': [1, 2, 3, 1, 2, 1], 'b': [1, 2, 3, 1, 2, 1], 'c': [1, 2, 3, 1, 2, 1]}

1 Answer

0 votes
by (36.8k points)

Use the below code: 

list_a = [("a", 1), ("b", 2), ("a", 3), ("b", 1), ("a", 2), ("c", 1)]

new_dict = {}

for item in list_a:

    # checking the item[0] which gives the first element

    # of a tuple which is there in the key element of 

    # of the new_dict

    if item[0] in new_dict:

        new_dict[item[0]].append(item[1])

    else:

        # add a new data for the new key 

        # which we get by item[1] from the tuple

        new_dict[item[0]] = [item[1]]

print(new_dict)

Output:

{'a': [1, 3, 2], 'b': [2, 1], 'c': [1]}

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch 

Browse Categories

...