Reputation: 83
I am a beginner in python, and I would like to create a simple program that assigns each element in list1 to its respective element in list2 using the zip function.
list1=[1,2,3,4,1]
list2=[2,3,4,5,6]
dictionary=dict(zip(list1,list2))
print(dictionary)
However, because I have a duplicate value in list1, the dictionary displays the following results:
{1: 6, 2: 3, 3: 4, 4: 5}
Because 1 is a duplicate value in list1, only 1:6 is displayed and not 1:2 as well. How can I change my code such that the duplicate value is taken into account and is displayed in its respective order?
{1: 2, 2: 3, 3: 4, 4: 5, 1: 6}
Thank you
Upvotes: 0
Views: 435
Reputation: 22544
What you ask is not possible with a Python dict
, since that goes against the definition of a dict--keys must be unique. The comments explain why that is the case.
However, there are multiple other ways that may be useful to you that can achieve almost the same affect. One simple, yet not terribly useful, way is:
almost_dictionary = list(zip(list1, list2))
This gives the result
[(1, 2), (2, 3), (3, 4), (4, 5), (1, 6)]
which sometimes can be used like a dictionary. However, this probably is not what you want. Better is a dict
or defaultdict
that, for each key, holds a list
of all the values connected with that key. The defaultdict
is easier to use, though harder to set up:
dictionary = defaultdict(list)
for k, v in zip(list1, list2):
dictionary[k].append(v)
print(dictionary)
This gives the result
defaultdict(<class 'list'>, {1: [2, 6], 2: [3], 3: [4], 4: [5]})
and you see that each key has each value--the values are just in lists. The value of dictionary[1]
is [2, 6]
, so you have both values to work with.
Which method you choose depends on your purpose for the dictionary.
Upvotes: 2