Dictionaries

A dictionary contains key-value pairs. To create a dictionary, use a pair of curly brackets. To create an empty dictionary, leave the brackets empty. To create a dictionary with data, put key-value pairs inside of the brackets. Examples:
empty_dict = {}
student = {"name": "Tom", "age": 17, "height": 68}
To get a value from the dictionary above, use square brackets with the corresponding key:
print(student["age"])
# 17
To add a key-value pair to the dictionary, or to update a value in the dictionary, use the = operator:
# adds new key-value pair
student["year"] = 11
print(student["year"])
# 11

# updates existing key-value pair
student["age"] = 18
print(student["age"])
# 18
To check if a particular key is in the dictionary, use the in keyword:
print("name" in student) # True
print("grade" in student) # False
To remove a key-value pair from the dictionary, use the del keyword with the key:
del student["height"]
print(student["height"])

# Traceback (most recent call last):
#   File "main.py", line 3, in <module>
#     print(student["height"])
# KeyError: 'height'

Exercise 1 of 9

Initialize an empty dictionary called students.

Your code

Exercise 2 of 9

Initialize an empty dictionary called word_counts.

Your code

Exercise 3 of 9

Initialize a dictionary called info with the key-value pairs ("name", "Jordan"), ("age", 16), and ("height", 54).

Your code

Exercise 4 of 9

Update a dictionary called info so that "name" now has a value of "Sam".

Your code

Exercise 5 of 9

Update a dictionary called info so that "age" now has a value of 23.

Your code

Exercise 6 of 9

Add the key "year" to a dictionary called info with the value 1998.

Your code

Exercise 7 of 9

Write a condition to check if a dictionary called info contains the key "year".

Your code

Exercise 8 of 9

Write a condition to check if a dictionary called info contains the key "location".

Your code

Exercise 9 of 9

Delete the key "age" from a dictionary called info.

Your code