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