Watch Me Code 2: Dictionary Methods


In [15]:
student = { 'Name' : 'Michael', 'GPA': 3.2, 'Ischool' : True }
print(student)


{'Ischool': True, 'GPA': 3.2, 'Name': 'Michael'}

In [16]:
# KeyError, keys must match exactly
student['gpa']


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-16-962c3d448a23> in <module>()
      1 # KeyError, keys must match exactly
----> 2 student['gpa']

KeyError: 'gpa'

In [17]:
try:
    print(student['Age'])
except KeyError:
    print('The key "Age" does not exist.')


The key "Age" does not exist.

In [18]:
list(student.values())


Out[18]:
[True, 3.2, 'Michael']

In [19]:
list(student.keys())


Out[19]:
['Ischool', 'GPA', 'Name']

In [20]:
for key in student.keys():
    print(student[key])


True
3.2
Michael

In [21]:
del student['GPA']
print(student)


{'Ischool': True, 'Name': 'Michael'}