2015-11-13 154 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]