Dictionaries
grades = {'kevin': 30, 'jabari': 25}
# Let's say kevin and jabari both need to study, ASAP
# With a dictionary we can get their grades as follows:
grades['kevin'] # 30
grades['jabari'] # 25
# Let's get more practice
# Multi-line dictionaries normally have the brackets spanning a few lines
student_profile = {
'name': 'roger rabbit',
'age': 14,
'courses': ['programming', 'maths', 'english', 'spanish'],
'loves code': True
}
# You can store almost any type as the value, make the keys consistent
student_profile['name'] # 'roger rabbit'
student_profile['courses'][-2] # 'english'
# You can add key-value pairs as well
student_profile['mentor'] = 'plato'
student_profile # {'courses': ['programming', 'maths', 'english', 'spanish'], 'loves code': True, 'mentor': 'plato', 'name': 'roger rabbit', 'age': 14}
# Your order may be different, that's fine. Dictionaries don't keep order
if student_profile['loves code']:
print('yayy')Exercises
Last updated