Loading...
Loading...
Store key-value pairs with dictionaries
A dictionary (dict) stores data in key-value pairs. Instead of numbered positions like a list, dictionaries use meaningful keys (usually strings) to label each value. Think of it like a real dictionary — you look up a word (key) to find its definition (value).
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(person["name"]) # "Alice" — access by key
print(person.get("age")) # 25 — safer access (no error if missing)| Part | What it means |
|---|---|
| `{ }` | Curly braces create a dictionary |
| `"name"` | **Key** — like a variable name (unique identifier) |
| `:` | Separates key from value |
| `"Alice"` | **Value** — can be any type: string, number, list, even another dict |
| `,` | Separates key-value pairs |
student = {
"name": "Bob",
"grades": [85, 92, 78],
"active": True,
"id": 12345
}
print(student["name"]) # "Bob"
print(student["grades"][0]) # 85 — value can be a list!
print(student.get("phone")) # None — key doesn't exist, returns None safely
# print(student["phone"]) # ❌ KeyError! Use .get() for safetysettings = {"theme": "dark", "volume": 80}
settings["volume"] = 50 # Update existing key
settings["language"] = "en" # Add new key-value pair
del settings["theme"] # Remove a key
print(settings) # {"volume": 50, "language": "en"}capitals = {"USA": "Washington", "France": "Paris", "Japan": "Tokyo"}
print(capitals.keys()) # dict_keys(["USA", "France", "Japan"])
print(capitals.values()) # dict_values(["Washington", "Paris", "Tokyo"])
print(capitals.items()) # dict_items([("USA", "Washington"), ...])| ❌ Wrong | Why | ✅ Right |
|---|---|---|
| `dict[0]` when keys are strings | Lists use index numbers, dicts use keys | `dict["name"]` |
| `dict = {}` then `dict["key"]` works but... | Avoid naming variables `dict` — shadows the built-in | Use `data = {}` |
| `student["phone"]` when key doesn't exist | Causes KeyError! | Use `student.get("phone")` |
| `{"name": "Alice", "name": "Bob"}` | Duplicate keys — second overwrites first | Keep keys unique |
Create a dictionary called movie with:
Then print: "My favorite movie is {title} from {year}. I rate it {rating}/10."
movie = {"title": "Inception", "year": 2010, "rating": 9.5}
print(f"My favorite movie is {movie["title"]} from {movie["year"]}. I rate it {movie["rating"]}/10.")