Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge two lists to make dictionary with same key Python

I would like to know how to change this code to NOT using the function zip. I haven’t been taught this function yet and so I want to know if there is an alternative way to retrieve the output I require?

list_one = ['a', 'a', 'c', 'd']
list_two = [1, 2, 3, 4]

dict_1 = {}

for key, value in zip(list_one, list_two):
    if key not in dict_1:
        dict_1[key] = [value]
    else:
        dict_1[key].append(value)

print(dict_1)

I would like the output to be:

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

zip() makes it easy to iterate through multiple lists in parallel. If you try to understand the zip() it would be very easy to replicate it. So, please find the explanation and example in the official docs here.

Below is an example code with the implementation,

list_one = ['a', 'a', 'c', 'd']
list_two = [1,2,3,4]

dict_1={}
for index in range(len(list_one)):
    if list_one[index] not in dict_1:
        dict_1[list_one[index]]=[list_two[index]]
    else:
        dict_1[list_one[index]].append(list_two[index])
print(dict_1)

Output:

{'a': [1, 2], 'c': [3], 'd': [4]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading