The first number is the student id, the second is the code of the course.
course = ["001, aly6015", "002, aly6050", "001, aly6020", "003, aly6070", "001, aly6140"]
dict = {}
for i in course:
I want to build a dictionary like the following: when I input dict['001']
then the output comes as aly6015, aly6020, aly6140
I don't know how to read value from the course list so that I can append 001, 002, 003 as keys in my dictionary and course code as values in my dictionary.
Thank you very much!
from collections import defaultdict
d = defaultdict(list)
for item in course:
sid, cid = item.split(', ')
d[sid].append(cid)
Try this
courses = ["001, aly6015", "002, aly6050", "001, aly6020", "003, aly6070", "001, aly6140"]
d = {}
for course in courses:
key, value = course.split(",")
if key in d:
d[key].append(value)
else:
d[key] = [value]
print(d)
Output:
{'001': [' aly6015', ' aly6020', ' aly6140'], '002': [' aly6050'], '003': [' aly6070']}
You can split each course on ", "
, then group withdict.setdefault
:
courses = ["001, aly6015", "002, aly6050", "001, aly6020", "003, aly6070", "001, aly6140"]
d = {}
for course in courses:
student_id, course_code = course.split(", ")
d.setdefault(student_id, []).append(course_code)
print(d)
# {'001': ['aly6015', 'aly6020', 'aly6140'], '002': ['aly6050'], '003': ['aly6070']}
But its probably nicer to use collections.defaultdict
, as shown by @Steven Rumbalski
Its also not a good idea to use dict
as a variable name, as it shadows the builtin function dict()
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.