简体   繁体   中英

Reading file and storing in dictionary

im going over dictionaries and i dont really get how to construct your own. I have the following data in a csv file

fp = CpE, CSE 2315
     CpE, CSE 2320
     CpE, CSE 2441
     CpE, CSE 3320
     CpE, CSE 3442
     CpE, EE 2440
     CpE, MATH 1426
     CS, CSE 2315
     CS, CSE 2320
     CS, CSE 3320
     CS, CSE 4303
     CS, CSE 4305
     CS, CSE 4308
     CS, MATH 1426
     SE, CSE 2315
     SE, CSE 2320
     SE, CSE 3311
     SE, CSE 3320
     SE, CSE 4321
     SE, CSE 4322
     SE, CSE 4361
     SE, MATH 1426

I want to store this information in a dictionary in the following format so that each degree is its own key, followed by all the classes in that degree

{'Cpe' : ['CSE 2315', 'CSE 2320', 'CSE 2441'.........],
 'CS' : ['CSE 2315', 'CSE 2320'....................],

here is what i wrote to try to do it but im having trouble

 majors = { }
    for line in fp :
        degree, course = line.strip().split(',')   ##split the componets of each line
        if degree in majors :                # if degree is already in dictionary,add class
            majors[degree] = {course}
        else :                               #if degree is not in dictionary add degree and class  
            majors[degree] = {degree,course}
    return majors

but when i print i get

{'CS': set(['MATH 1426']), 'CpE': set(['MATH 1426']), 'SE': set(['MATH 1426'])}

help?

majors[degree] = {course}
...
majors[degree] = {degree,course}

{...} notation what you used here corresponds to sets in python. So you are actually creating a set when you actually need a list. You can use this

majors = {}
for line in fp :
    degree, course = line.strip().split(',')
    majors.setdefault(degree, []).append(course)
return majors

You can use a defaultdict to create a lists corresponding to the keys like this

from collections import defaultdict
majors = defaultdict(list)
for line in fp :
    degree, course = line.strip().split(',')
    majors[degree].append(course)
return majors

defaultdict is a subclass of dict . So you can use it like a 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.

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