yulai
yulai

Reputation: 761

Python: Merge two lists to dictionary

I have the following lists in Python:

students = ["Anderson", "Peter", "Anderson", "Bastian"]
courses = ["Biology", "History", "Maths", "History"]

I have coded a for loop in an attempt to relate these pairs in a dictionary, so that:

Anderson-Biology
Peter-History
Anderson-Maths
Bastian-History

The for-loop is as follows:

test_dict = {}
for i in range (0, len(students)):
    test_dict[students[i]] = courses[i]

However, when printing out the dictionary, I get:

{'Bastian': 'History', 'Anderson': 'Maths', 'Peter': 'History'}

What has happened to 'Anderson': 'Biology, and is there a way I can solve this?

Upvotes: 1

Views: 128

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

Python dictionaries doesn't accepts duplicate keys and in your code it just preserve the last 'Anderson'.

Instead you can use dict.setdefault method to put the duplicated values in a list :

>>> d={}
>>> for i,j in zip(students,courses):
...   d.setdefault(i,[]).append(j)
... 
>>> d
{'Peter': ['History'], 'Anderson': ['Biology', 'Maths'], 'Bastian': ['History']}
>>> 

Upvotes: 9

Related Questions