我想創建一個函數,只打印參數中給定的鍵的值。但它並沒有完成我想要的事情。請看看我的代碼,看看我錯在哪裏?由於如何打印字典中的鍵值?
list = {
"David": 42,
"John": 11,
"Jack": 278
}
def get_marks(student_name):
for marks in list.items():
print(marks)
get_marks("David")
我想創建一個函數,只打印參數中給定的鍵的值。但它並沒有完成我想要的事情。請看看我的代碼,看看我錯在哪裏?由於如何打印字典中的鍵值?
list = {
"David": 42,
"John": 11,
"Jack": 278
}
def get_marks(student_name):
for marks in list.items():
print(marks)
get_marks("David")
您正在嘗試這樣的:
def get_marks(student_name):
print(list.get(student_name))
您可以使用my_dict[student_name]
一鍵訪問值,但使用字典的get
方法是因爲它返回None
時,最關鍵的不是更安全發現:
def get_marks(student_name):
print my_dict.get(student_name)
我已經改名爲你的字典從list
到my_dict
以避免陰影內建列表類。
list = {
"David": 42,
"John": 11,
"Jack": 278
}
def get_marks(student_name):
print list[student_name]
get_marks("David")
您可以使用字典的get()方法,像這樣:
def get_marks(student_name):
return list.get(student_name)
,或者你也可以只使用basic dictionary access (Section 5.5)和處理你自己丟失的鑰匙:
def get_marks(student_name):
if student_name in list:
return list[student_name]
else:
#Key not in dict, do something
嗯,'打印(列表[student_name])'? –
@Rawing如果元素不存在,使用dict的get函數可以防止你得到一個關鍵錯誤 – HolyDanna
http://stackoverflow.com/questions/5904969/python- how-to-print-a-dictionarys-key –