简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM