2014-11-03 23 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]打印 '英国人'

访问列表