2014-11-03 24 views
0

我有一本字典,我想要使用函數打印代碼。我無法讓我的功能工作,不理解爲什麼它不是從我的字典中打印學生。在python中打印字典中的條目

def getstudent(key): 
    students = {'23A' :['Apple', 'John', 95.6], 
       '65B' :['Briton', 'Alice', 75.5], 
       '56C' :['Terling', 'Mary', 98.7], 
       '68R' :['Templeton', 'Alex', 90.5]} 

我想,然後運行getstudent(「65B」)的功能和類型,但是當我跑我沒有得到任何回報。

謝謝!

+0

您未打印任何內容。你正在創建學生詞典 – Andy 2014-11-03 18:16:38

+0

爲什麼使用函數,當你可以直接使用students.get('65B') – Beginner 2014-11-03 18:16:41

回答

1

您沒有使用key參數或在函數返回任何東西:

def getstudent(key): 
    students = {'23A' :['Apple', 'John', 95.6], 
       '65B' :['Briton', 'Alice', 75.5], 
       '56C' :['Terling', 'Mary', 98.7], 
       '68R' :['Templeton', 'Alex', 90.5]} 
    return students.get(key) # return 

print(getstudent('65B')) 
['Briton', 'Alice', 75.5] 

或者忘了功能,只是直接與students.get(key)訪問字典。

您可能還希望輸出的信息性消息,如果該鍵不存在,通過傳遞一個默認值來獲得它可以做到:

students.get(key,"Key does not exist") 
+0

+1只是使用內建的 – Wyrmwood 2014-11-03 18:30:37

0

沒有任何錯誤檢查:

def getstudent(key): 
    students = {'23A' :['Apple', 'John', 95.6], 
       '65B' :['Briton', 'Alice', 75.5], 
       '56C' :['Terling', 'Mary', 98.7], 
       '68R' :['Templeton', 'Alex', 90.5]} 
    print(students[key]) 

getstudent('65B') 
0

像這樣嘗試

def getstudent(key): 
    students = {'23A' :['Apple', 'John', 95.6], 
       '65B' :['Briton', 'Alice', 75.5], 
       '56C' :['Terling', 'Mary', 98.7], 
       '68R' :['Templeton', 'Alex', 90.5]} 
    if key in students.keys():  # to handle if key is not present 
     return students[key] 
    else: return "No key found" 
getstudent('65B') 

輸出:

['Briton', 'Alice', 75.5] 

你需要返回值

如何解釋工作,詞典有一對叫,key及其value。 字典的值可以通過其鍵值獲取。所以我在這裏做什麼。當你用鍵調用一個函數。我提取基於關鍵字的值,例如students[key]它會爲您提供字典中的鍵值。
students.keys()會給你所有關鍵的名單在字典

+0

你不打印或返回值 – Hackaholic 2014-11-03 18:20:55

0
def getstudent(key): 
    students = {'23A' :['Apple', 'John', 95.6], 
       '65B' :['Briton', 'Alice', 75.5], 
       '56C' :['Terling', 'Mary', 98.7], 
       '68R' :['Templeton', 'Alex', 90.5]} 
    if key in students: 
     return students[key] 
    else: 
     return "%s is not a valid key" % (key) 

如果運行getstudent( '65B'),你會得到一個列表

[ '英國人', '愛麗絲',75.5]

然後你可以通過索引例如

a_student = getstudent('65B') # now a_student list is as ['Briton', 'Alice', 75.5] 
print a_student[0] 

a_student [0]打印 '英國人'

訪問列表