Python Dictionary Methods

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: Alex
age: 28
city: Berlin

Note

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

Alex
None

See 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 file
Berlin

The 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 age went from 28 to 29.
  • If the key is new, it gets added. So email was 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 remove

Caution

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 there
email = person["email"]
# βœ… Good: returns a default instead of crashing
email = 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 missing
person.pop("phone")
# βœ… Good: safe, returns the default
person.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() and pop() 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(), and items() to read the parts of a dictionary, with items() being the go-to for looping.
  • βœ… get() as the safe way to read a key, returning None or 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. 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. 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. 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. 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.

Nested Dictionaries

Share & Connect