如何将文件读入字典,然后排序并添加索引?

时间:2018-10-03 04:56:35

标签: python dictionary

如果文件如下所示:

SID,Grade
1,99
2,100
3,55
4,60

我如何将其读入python并转换成这样的结果:

Dict=readGrades(’grades.csv’)

读取100个值。

gDict{’1’:99,  ’2’:100,  ’3’:55, ...}

然后按等级对成绩进行排序

computeRank(gDict)
gDict{’1’:(99,2),’2’:(100,1),’3’:(55,4), ...}

1 个答案:

答案 0 :(得分:0)

def readGrades(filename):
    result = dict()
    with open(filename) as f:
        for line in f:
            key, val = line.split(",")
            result[key] = int(val.strip())
    return result

def computeRank(dic):
    rank = sorted(list(dic.values())); rank.reverse()
    for key in dic.keys():
        dic[key] = (dic[key], rank.index(dic[key]))

您可以尝试这样