Q1For d = {"a": 1, "b": 2}, which one doesn't raise an error when you look up a missing key?
How to Use Python Dictionaries (dict)
Learn how the Python dict type stores key-value pairs and how to add, update, and look up entries safely in your browser.
Creating a dictionary
A dictionary (dict) is a type that stores values as key-value pairs.
Where a list is a box you pull values from by position (0, 1, 2…), a dict is a box you pull values from by name (key) — that's the easiest mental model.
Wrap with { } and list key: value pairs separated by commas.
The key is the name, the value is the contents. Keys must be unique.
# Declare a dictionary
car = {
"brand": "Toyota",
"model": "Prius",
"year": 2015,
}
print(car) # {'brand': 'Toyota', 'model': 'Prius', 'year': 2015}
print(type(car)) # <class 'dict'>
# Keys don't have to be strings (numbers work too)
score_by_id = {1: 80, 2: 95, 3: 72}
print(score_by_id[2]) # 95
When to use list vs dict
If order or position matters, use list. If you want to look up by name, use dict.
For example, 'a ranking of 3 scores' is a list; 'scores per user' is a dict.
Even for the same data, how you want to retrieve it decides which one to pick.
Retrieving values — [] vs .get()
There are two ways to pull a value out of a dict, and the key difference is how they behave when the key doesn't exist.
.get() lets you pass a default value as the second argument — that's the handy part.
You can say 'return this if the key isn't there' in a single line.
car = {"brand": "Toyota", "model": "Prius", "year": 2015}
# ① Access with []
print(car["brand"]) # Toyota
# print(car["color"]) # KeyError: 'color'
# ② Access with .get()
print(car.get("brand")) # Toyota
print(car.get("color")) # None
print(car.get("color", "Unknown")) # Unknown (the second arg is returned)
.get() to keep running, [] to stay strict
If a missing key means something is broken, [] is safer — it surfaces the problem early as an error.
If it's fine either way (e.g., optional settings), passing a default to .get() reads better and cuts down on exception handling (covered later).
Add, update, delete
Dicts, like lists, can be modified after they're created.
The simplest way to add, update, and delete is direct assignment.
| What to do | Syntax | Key point |
|---|---|---|
| Add or update | d["key"] = value | Updates if the key exists, adds if not |
| Update multiple at once | d.update(other_dict) | Overwrites overlapping keys, adds new ones |
| Pop and delete | v = d.pop("key") | Deletes and stores the value. Missing key raises KeyError |
| Empty it out | d.clear() | The dict object stays, contents are emptied |
| Delete the variable | del d | Deletes d itself. Later references raise an error |
The same syntax adds when the key is missing and updates when it's there.
The dict decides 'create if missing, overwrite if present' for you.
car = {"brand": "Toyota", "model": "Prius", "year": 2015}
# Add (new key)
car["color"] = "white"
print(car)
# {'brand': 'Toyota', 'model': 'Prius', 'year': 2015, 'color': 'white'}
# Update (existing key)
car["year"] = 2024
print(car["year"]) # 2024
# Update multiple at once
car.update({"country": "JP", "model": "Camry"})
print(car["model"]) # Camry (overwritten)
print(car["country"]) # JP (newly added)
# Pop and delete
old_year = car.pop("year")
print(old_year) # 2024
# print(car["year"]) # KeyError (gone now)
# Empty it out
car.clear()
print(car) # {}
Listing keys/values & checking existence
Last up: the tools for inspecting a dict.
There are 4 main ones — keys() / values() / items() / the in operator.
- keys() — returns the list of keys (
dict_keys(['brand', 'model', ...])) - values() — returns the list of values
- items() — returns the list of key-value pairs (usually paired with a
forloop) - "key" in dict — returns True / False depending on whether the key exists
Same dict, different calls depending on what you want to pull out.
keys / values / items return lists; in returns True / False.
car = {"brand": "Toyota", "model": "Prius", "year": 2015}
print(car.keys()) # dict_keys(['brand', 'model', 'year'])
print(car.values()) # dict_values(['Toyota', 'Prius', 2015])
print(car.items()) # dict_items([('brand', 'Toyota'), ...])
# Check for key existence (typically combined with if)
print("brand" in car) # True
print("color" in car) # False
if "brand" in car:
print("Maker: " + car["brand"])
else:
print("No maker info")
Combining for with items() (reference)
To iterate over a dict one item at a time, the standard form is for key, value in car.items():.
We'll cover for in a later chapter, so we won't dive deep here — but remember just this: items() lets you pull the key and value out together.
In this article you learned how to declare a dict, how [] and .get() differ when retrieving, how to add, update, and delete entries, and how to check key existence and list contents.
Dicts show up everywhere in real work — user info, settings, stock, summary results. Once you internalize the image of a box you look up by key, you'll feel right at home with the data processing that comes next.
Knowledge Check
Answer each question one by one.
Q2After running d["a"] = 2 on d = {"a": 1}, what is d?
Q3Which method returns the list of keys?