简体   繁体   English

读取文件并存储在字典中

[英]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 我在csv文件中有以下数据

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. {...}符号你在这里使用的对应于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 您可以使用defaultdict创建与此键对应的列表

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 . defaultdictdict的子类。 So you can use it like a dict . 所以你可以像dict一样使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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