In this section, we're going to learn about dictionaries. A
dictionary is similar to a list in that they both hold multiple values
at a time, but they differ in some important ways. In a list, each
value is accessed using its index, which is automatically
assigned as you add new elements. With a dictionary, elements are
accessed using their keys, which the programmer creates as
they build the dictionary.
To create a dictionary in Python, we use a pair of curly braces, and
just like with a list, we can either leave them empty to create an
empty dictionary, or initialize it with data:
empty_dict = {}
student = {"name": "Tom", "age": 17, "height": 68}
Each item in the dictionary consists of a key/value pair separated by a
colon, and each pair is separated by a comma. The item before the colon
is the key, and the item after the colon is the value.
To access a particular value, we use the same square brackets as we
would with a list, except we put the corresponding key instead of an
index:
print(student["age"])
# 17
To add an element to the dictionary, we pretend as though the key we
want to use already exists, and assign it a value with the equals
operator:
student["year"] = 11
print(student["year"])
# 11
If the key does exist already, the existing value will be updated, and
no new keys will be added:
student["age"] = 18
print(student["age"])
# 18
To check if the dictionary contains a particular key, we can use
in
, just like we would with a list:
print("name" in student) # True
print("grade" in student) # False
We delete a key/value pair the same way we would delete an element in a
list, using the del
keyword:
del student["height"]
print(student["height"])
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# KeyError: 'height'