2015-11-13 65 views
-1

嗨,我很努力追加两个值到字典,请参阅下面的代码,但我想追加平均分数到他们的名字。Python字典问题

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 
+0

你想存储/什么样的信息,你已经存储在你的'Classdict'? –

回答

1

从外观上来看,这条线是错误的:

AvgDict[key] = Avg 

我认为应该改为:

AvgDict[key] = [Avg] 

,让你有,你可以添加到列表。

所附的代码也可以写成这样,我觉得看起来有点清晰:

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

当值分配给AvgDict,确保你把它作为一个清单,否则,当您使用.append(Avg),它不起作用。 一个可以implenet这样的:

AvgDict[key] = [Avg]