簡體   English   中英

讀取文件並存儲在字典中

[英]Reading file and storing in dictionary

即時通訊字典,我真的不知道如何構建自己的字典。 我在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

我想以下列格式將這些信息存儲在字典中,以便每個學位都是自己的關鍵,然后是該學位的所有課程

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

這是我寫的嘗試去做但我遇到麻煩

 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

但是當我打印我得到

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

救命?

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

{...}符號你在這里使用的對應於python中的集合。 因此,當您確實需要列表時,實際上是在創建一個集合。 你可以用它

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

您可以使用defaultdict創建與此鍵對應的列表

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

defaultdictdict的子類。 所以你可以像dict一樣使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM