我有一本字典,我正在尝试使用函数打印代码。我无法让我的功能工作,也无法理解为什么它不会从我的字典中打印出来。
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 :(得分: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)
直接访问dict。
如果密钥不存在,您可能还希望输出信息性消息,这可以通过将默认值传递给get来完成:
students.get(key,"Key does not exist")
答案 1 :(得分: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')
答案 2 :(得分: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()
会为您提供字典中所有键的列表
答案 3 :(得分: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'),您将获得一个列表
['Briton','Alice',75.5]
然后您可以通过索引来访问列表,例如
a_student = getstudent('65B') # now a_student list is as ['Briton', 'Alice', 75.5]
print a_student[0]
a_student [0]打印'英国人'