Dictionaries: Keys and Values
A dictionary (dict) stores key to value pairs. Instead of looking things up by position, you look them up by a name.
person = {"name": "Ada", "age": 36}
print(person["name"]) # Ada
print(person["age"]) # 36Keys are usually strings. Each key must be unique. To add a new pair or update an existing one, assign to the key:
person["city"] = "London" # add a new key
person["age"] = 37 # update an existing key
print(person)
# {'name': 'Ada', 'age': 37, 'city': 'London'}Check whether a key exists with in:
print("name" in person) # True
print("email" in person) # FalseLooking up a key that does not exist with square brackets raises a KeyError. The next lesson shows a safer way.
Build a dict book with keys "title" set to "Dune" and "pages" set to 412. Then add a key "author" set to "Herbert", and update "pages" to 500.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.