Contact
Evil Genius SocietyHomeLearnForumLeaderboardSocialsMessages
← Back to module

Lesson 5 of 10

A list stores values by position. A dictionary stores them by name — you look things up with a meaningful key instead of remembering that the email happens to be at index 2.

person = {"name": "Ada", "age": 36, "city": "London"}
print(person)
print(person["name"])

Curly braces, and each entry is a key: value pair. Keys are usually strings; values can be anything.

Compare the two approaches:

person_list = ["Ada", 36, "London"]
print(person_list[1])

person_dict = {"name": "Ada", "age": 36, "city": "London"}
print(person_dict["age"])

person_dict["age"] says what it means. person_list[1] requires you to remember the layout.

Reading values

person = {"name": "Ada", "age": 36}

print(person["name"])
print(person.get("age"))
print(person.get("email"))
print(person.get("email", "not provided"))

Square brackets raise a KeyError if the key is missing. .get() returns None instead, or a default you supply. Use .get() whenever a key might legitimately be absent.

Adding and updating

There is no separate "add" — assigning to a key creates it if it doesn't exist, and overwrites it if it does.

person = {"name": "Ada"}

person["age"] = 36
print(person)

person["age"] = 37
print(person)

Removing

person = {"name": "Ada", "age": 36, "city": "London"}

del person["city"]
print(person)

age = person.pop("age")
print(age)
print(person)

del deletes a key. .pop() deletes it and returns the value.

Checking for a key

person = {"name": "Ada", "age": 36}

print("name" in person)
print("email" in person)
print(len(person))

in checks keys, not values. len() counts the pairs.

Rules for keys

Keys must be immutable — strings, numbers, and tuples work; lists do not. Keys are also unique: assigning to an existing key replaces its value rather than adding a second entry.

scores = {"ada": 90, "grace": 95}
scores["ada"] = 100
print(scores)

Try it yourself

Build a dictionary for a book with title and year, add an author, then print the title and the number of keys.

Checkpoint

  • Dictionaries map keys to values: {"key": value}.
  • d[key] raises KeyError when missing; d.get(key, default) is the safe version.
  • Assigning to a key adds or updates it; del and .pop() remove it.
  • in checks keys; keys must be unique and immutable.

Questions about this lesson

Log in to ask a question.