Level 1
0 / 100 XP

Creating and using dicts

A dictionary holds key–value pairs. You write it with curly braces {}, putting a colon between each key and its value.

Creating a dict

Python
user = {"name": "Alice", "age": 30, "city": "Springfield"}

Each pair is key: value, and pairs are separated by commas. Keys are usually strings, but values can be any type.

Accessing values

Look up a value by putting its key in square brackets:

Python
user = {"name": "Alice", "age": 30} print(user["name"]) # Alice print(user["age"]) # 30

If you ask for a key that doesn't exist, Python raises a KeyError.

Adding and updating

Assign to a key to add it (if new) or update it (if it already exists):

Python
user = {"name": "Alice", "age": 30} user["city"] = "Springfield" # add a new key user["age"] = 31 # update an existing key print(user) # {'name': 'Alice', 'age': 31, 'city': 'Springfield'}

Key takeaways

  • Create a dict with {} and key: value pairs.
  • Read a value with d["key"].
  • d["key"] = value adds a new key or updates an existing one.