Python字典问题

时间:2015-11-13 22:58:10

标签: python dictionary

您好我正在努力将两个值附加到字典中,请参阅下面的代码,但我想将平均分数附加到他们的名字上。

 Question = raw_input("""How would you like to view the class?
 A) By Average, highest to lowest:
B) By Highest score, highest to lowest:
C) By Alphaetical order:
""")
Question = Question.title()
if Question == "A" :
    for key, value in Classdict.items():
        Avg = sum(map(int, value))/ float(len(value))
        global AvgDict
        AvgDict = {}
        for key in Classdict:
            if key in AvgDict:
                AvgDict[key].append(Avg)
            else:
                AvgDict[key] = Avg
        print AvgDict
    Classopen.close()
    Questiontwo = raw_input("""How would yuu like to view it?
A)By highest score, highest to lowest:
B)By Alphaetical order: 
""")

    Questiontwo = Questiontwo.title()
    if Questiontwo == "A":
        print "You selected highest score, highest to lowest"
        sortedavghigh = sorted(AvgDict.items(), key=operator.itemgetter(1))
        print sortedavghigh[::-1]
    elif Questiontwo == "B":
        print "You selected to sort it alphabetically"
        sortedavgapha = sorted(AvgDict.items(), key=operator.itemgetter(0))
        print sortedavgalpha

2 个答案:

答案 0 :(得分:1)

从它的外观来看,这一行是错误的:

AvgDict[key] = Avg

我认为应该是:

AvgDict[key] = [Avg]

这样您就可以附加一个列表。

附加代码也可以这样写,我觉得看起来更清晰:

if key not in AvgDict:
    AvgDict[key] = []
AvgDict[key].append(Avg)

答案 1 :(得分:0)

AvgDict分配值时,请确保将其作为列表放置,否则,当您使用.append(Avg)时,它不起作用。 人们可以像这样实现它:

AvgDict[key] = [Avg]