-2

I'm trying to create a function that prints out just the value of the key given in the parameter. But it isn't quite doing what I want it to do. Please have a look at my code and see where I'm wrong? Thanks

list = {
    "David": 42,
    "John": 11,
    "Jack": 278
}

def get_marks(student_name):
    for marks in list.items():
        print(marks)

get_marks("David")

4 Answers4

0

You are trying this:

def get_marks(student_name):
    print(list.get(student_name))
okuznetsov
  • 278
  • 1
  • 5
  • 12
0

You can access the value at a key using my_dict[student_name] but using the get method of the dictionary is much safer as it returns None when the key is not found:

def get_marks(student_name):
    print my_dict.get(student_name)

I have renamed your dictionary from list to my_dict to avoid shadowing the builtin list class.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0
list = {
"David": 42,
"John": 11,
"Jack": 278
}

def get_marks(student_name):
    print list[student_name]

get_marks("David")
khelili miliana
  • 3,730
  • 2
  • 15
  • 28
0

You can either use the get() method of the dictionary like so:

def get_marks(student_name):
    return list.get(student_name)

or you can just use basic dictionary access (Section 5.5) and handle missing keys on your own:

def get_marks(student_name):
    if student_name in list:
        return list[student_name]
    else:
        #Key not in dict, do something