All lessons
πŸ“–

Python Dictionaries

Key-value pairs for structured data

Reward
+60 XP

Creating a dictionary

Dictionaries store data as key:value pairs. Keys must be unique and immutable.

person = {
    "name": "Alice",
    "age": 30,
    "city": "NYC"
}
print(person["name"])

Modifying and iterating

Add, update, or delete entries. Loop through keys, values, or items.

d = {"a": 1, "b": 2}
d["c"] = 3
for k, v in d.items():
    print(k, v)

Try it yourself

Run the example below. Edit it and see what changes.

main.py
Output
Press Run to execute (Ctrl/Cmd+Enter)

Common mistakes

  • ⚠Using a non-existent key without .get() raises KeyError.
  • ⚠Keys must be immutable (strings, numbers, tuples) β€” not lists.