Syllabus Lesson 31 of 239 · Data Structures
Data Structures

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"])    # 36

Keys 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)  # False

Looking up a key that does not exist with square brackets raises a KeyError. The next lesson shows a safer way.

Your turn

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.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output