Python Dictionary Methods
Table of Contents + β
In the last lesson you learned Dictionary Operations, where you added, changed, and removed items by hand. Now we go one step further. A dictionary comes with its own set of built-in methods, ready to use. These methods read the data. They update it in bulk. They pull values out safely. Once you know them, you stop writing clumsy code. You start writing the short, clear kind.
π€ Why Dictionary Methods Matter
Here is the pain. You have a dictionary and you want to read a key. So you write user["age"]. But what if that key is not there? Python throws an error and your program crashes. Now imagine you want to loop over every key. Or merge two dictionaries together. Or pull out a value and remove it at the same time. Doing all that by hand is slow. It is also easy to get wrong.
Dictionary methods solve this. They are small built-in tools that do these common jobs for you. Each one takes a single clean line. The most useful one here is get(). It is the safe way to read a key that might not exist.
We will use one example dictionary all the way through. That way you can see each method working on the same data.
This is the dictionary we will use the whole lesson. It holds details about one person named Alex.
person = { "name": "Alex", "age": 28, "city": "Berlin",}print(person)Output
{'name': 'Alex', 'age': 28, 'city': 'Berlin'}π keys(), values(), and items()
Sometimes you do not want the whole dictionary. You just want the labels. Or just the data. Or both as pairs. These three methods give you exactly that.
Think of a dictionary like a contact card. The keys are the field names (name, age, city). The values are what is written in each field (Alex, 28, Berlin). The items are the full lines, label and value together.
This code shows all three methods on our person dictionary.
print(person.keys())print(person.values())print(person.items())Output
dict_keys(['name', 'age', 'city'])dict_values(['Alex', 28, 'Berlin'])dict_items([('name', 'Alex'), ('age', 28), ('city', 'Berlin')])Let me walk through what came back:
keys()gives you just the keys:name,age,city.values()gives you just the values:Alex,28,Berlin.items()gives you key-value pairs, each one wrapped in a small bracket like('name', 'Alex').
The most common use is looping. The items() method is perfect when you want both the key and the value at the same time.
This loop prints each field and its value on its own line.
for key, value in person.items(): print(f"{key}: {value}")Output
name: Alexage: 28city: BerlinNote
These three return special βviewβ objects, not plain lists. A view stays connected to the dictionary. So if the dictionary changes, the view shows the new data too. If you really need a list, wrap it: list(person.keys()).
π get() β the safe way to read a key
Now the important one. Reading a key with square brackets is risky. If the key is missing, your program stops with an error.
Watch what happens when we ask for a key that is not in the dictionary.
print(person["email"])Output
Traceback (most recent call last): File "main.py", line 1, in <module> print(person["email"])KeyError: 'email'That KeyError is the crash we want to avoid. The get() method is the fix. It reads the key if it exists. And if it does not, it quietly returns None instead of crashing.
This code reads one key that exists and one that does not, using get() for both.
print(person.get("name"))print(person.get("email"))Output
AlexNoneSee the difference? No crash. The missing key just gave back None.
You can also tell get() what to return when the key is missing. You pass a second value, and that becomes the fallback.
This code asks for email but says βif it is not there, give me this text insteadβ.
print(person.get("email", "no email on file"))print(person.get("city", "no city on file"))Output
no email on fileBerlinThe first line had no email, so it returned the fallback text. The second line found city, so it returned the real value and ignored the fallback.
Tip
Use get() whenever a key might not be there. Think of reading settings from a config, or fields from a form the user might leave blank. It keeps your program running instead of crashing on the first missing field.
β update() β change or add in bulk
You already know you can set one key at a time. But what if you want to change several keys at once? Or merge in a whole second dictionary? That is what update() is for.
This code changes age, and adds a brand new email key, all in one call.
person.update({"age": 29, "email": "alex@example.com"})print(person)Output
{'name': 'Alex', 'age': 29, 'city': 'Berlin', 'email': 'alex@example.com'}Here is the rule update() follows:
- If the key already exists, its value is replaced. So
agewent from28to29. - If the key is new, it gets added. So
emailwas added to the end.
It is one clean call instead of several separate lines.
π pop() β read and remove together
Sometimes you want to take a value out of the dictionary and also remove that key in the same move. The pop() method does both. It returns the value, then deletes the key.
This code pulls out the email we just added, and removes it from person.
removed_email = person.pop("email")print(removed_email)print(person)Output
alex@example.com{'name': 'Alex', 'age': 29, 'city': 'Berlin'}The value alex@example.com came back into our variable, and the email key is gone from the dictionary.
Like get(), pop() can take a fallback so it does not crash on a missing key.
This code tries to pop a key that is not there, but gives a default so the program keeps running.
phone = person.pop("phone", "no phone to remove")print(phone)Output
no phone to removeCaution
Without that second value, pop() on a missing key raises a KeyError, just like square brackets. If the key might be missing, always pass a default.
πͺΊ setdefault() β read, or set if missing
This one is a small helper that does two jobs in one. It reads a key if it exists. If the key does not exist, it adds it with a value you choose, and then returns that value.
This code asks for city, which already exists, so the default is ignored.
city = person.setdefault("city", "Unknown")print(city)print(person)Output
Berlin{'name': 'Alex', 'age': 29, 'city': 'Berlin'}The dictionary did not change because city was already there. Now watch what happens with a key that is missing.
This code asks for country, which is not in the dictionary, so setdefault() adds it.
country = person.setdefault("country", "Germany")print(country)print(person)Output
Germany{'name': 'Alex', 'age': 29, 'city': 'Berlin', 'country': 'Germany'}See the difference from get()? Both return a value for a missing key. But get() leaves the dictionary alone, while setdefault() actually writes the new key in.
π§Ή clear() β empty the whole thing
When you want to wipe a dictionary completely but keep the variable itself, use clear(). It removes every item and leaves you with an empty dictionary.
This code empties person in one call.
person.clear()print(person)Output
{}The variable still exists and still points to a dictionary. It is just empty now, ready to be filled again.
π Quick Reference
Here are all the methods from this lesson in one place.
| Method | What it does |
|---|---|
keys() | Returns all the keys |
values() | Returns all the values |
items() | Returns key-value pairs, great for looping |
get(key, default) | Safe read, returns the default if the key is missing |
update(other) | Changes or adds several keys at once |
pop(key, default) | Removes a key and returns its value |
setdefault(key, default) | Reads a key, or adds it if missing |
clear() | Removes every item, leaves an empty dictionary |
β οΈ Common Mistakes
Here are the common mistakes people make with these methods. Watch out for these.
Using square brackets for a key that might be missing. This is the number one cause of a KeyError.
# β Avoid: crashes if "email" is not thereemail = person["email"]
# β
Good: returns a default instead of crashingemail = person.get("email", "no email")Calling pop() on a missing key with no fallback. It crashes just like brackets do.
# β Avoid: KeyError if "phone" is missingperson.pop("phone")
# β
Good: safe, returns the defaultperson.pop("phone", None)Mixing up get() and setdefault(). Remember, get() only reads. setdefault() reads and may add a new key. If you only want to peek without changing anything, reach for get().
Trying to loop and change the dictionary at the same time. If you add or remove keys while looping over items(), Python complains. Loop over a copy if you need to change things, like for key in list(person.keys()):.
β Best Practices
- Reach for
get()by default when reading a key that may not exist. It saves you from surprise crashes. - Pass a sensible default to
get()andpop()so your code has a clear fallback value. - Use
items()when you loop and need both the key and the value. It reads cleanly. - Use
update()to merge dictionaries instead of writing many separate assignment lines. - Pick
clear()over making a fresh empty dictionary when other code is already pointing at the same one.
π§© What Youβve Learned
A quick recap of the methods you can now use.
- β
keys(),values(), anditems()to read the parts of a dictionary, withitems()being the go-to for looping. - β
get()as the safe way to read a key, returningNoneor a default instead of crashing. - β
update()to change or add several keys in one call, including merging another dictionary. - β
pop()to read a value and remove its key at the same time, with an optional default. - β
setdefault()to read a key, or add it with a default if it is missing. - β
clear()to empty a dictionary while keeping the variable itself.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does person.get("email") return if the key "email" is not in the dictionary?
Why: get() returns None for a missing key instead of crashing, unless you pass a different default as the second argument.
- 2
Which method gives you key-value pairs that are perfect for looping over both at once?
Why: items() returns the key and value together, so you can write `for key, value in person.items()`.
- 3
What is the difference between get() and setdefault() for a missing key?
Why: get() never changes the dictionary, but setdefault() writes the new key in when it is missing.
- 4
What does pop("age") do?
Why: pop() returns the value for the key and removes that key from the dictionary in one step.
π Whatβs Next?
You can now read, change, and clean up a flat dictionary with its own built-in methods. Next we go deeper, into dictionaries that hold other dictionaries inside them. That is how real-world data is usually shaped.