What you'll learn
- Quick answer
- What is a dictionary in Python?
- Reading values safely with get()
- Looping with keys(), values(), and items()
- Adding and merging with update()
- Removing keys with pop()
- Handling missing keys with setdefault()
- Real example: counting word frequency
- Common mistakes with Python dictionary methods
- FAQ
Quick Answer
A Python dictionary stores data as key-value pairs, and its built-in methods let you read, add, update, and remove that data safely. The ones you will use most are get() for safe lookups; keys(), values(), and items() for looping; update() to merge data; pop() to remove a key; and setdefault() to handle missing keys. Learning these seven methods covers almost everything a beginner needs.
What is a dictionary in Python?
If you have ever stored a contact's name next to their phone number, you already understand the idea behind a Python dictionary. A dictionary is a built-in Python type that stores data as key-value pairs. Each key points to a value, much like a word points to its meaning in a real dictionary.
In this guide we will walk through the most useful python dictionary methods one at a time, with a short, runnable example for each. By the end you will know how to read, add, update, and remove data without running into errors.
Here is a simple dictionary that stores details about a student:
student = {
"name": "Asha",
"age": 20,
"city": "Pune",
}
print(student["name"]) # Asha
print(student["age"]) # 20The keys here are "name", "age", and "city". The values are "Asha", 20, and "Pune". You look up a value by putting its key inside square brackets. Methods take this a step further, letting you work with the whole dictionary at once and avoid common errors.
Reading values safely with get()
Accessing a key that does not exist with square brackets raises a KeyError and stops your program:
student = {"name": "Asha", "age": 20}
print(student["city"]) # KeyError: 'city'The get() method solves this. It returns the value if the key exists, and None (or a default you choose) if it does not, without crashing.
student = {"name": "Asha", "age": 20}
print(student.get("name")) # Asha
print(student.get("city")) # None
print(student.get("city", "Unknown")) # UnknownThe second argument to get() is the fallback value. This makes get() the safest way to read data when you are not sure a key is present, such as with user input or values loaded from a file. It never changes the dictionary; it only reads from it.
Looping with keys(), values(), and items()
Once you have a dictionary, you often need to loop over it. Three methods help here:
keys()gives you all the keys.values()gives you all the values.items()gives you each key and value together as a pair.
student = {"name": "Asha", "age": 20, "city": "Pune"}
print(list(student.keys())) # ['name', 'age', 'city']
print(list(student.values())) # ['Asha', 20, 'Pune']
print(list(student.items())) # [('name', 'Asha'), ('age', 20), ('city', 'Pune')]The most common pattern is looping with items(), which unpacks each pair into two variables:
for key, value in student.items():
print(key, "=", value)
# name = Asha
# age = 20
# city = PuneOne note: these methods return special view objects, not plain lists. A view stays linked to the dictionary, so if the dictionary changes, the view reflects it. Wrap the result in list() when you need an actual list you can index into.
Adding and merging with update()
The update() method adds new key-value pairs or changes existing ones. You can pass another dictionary, and Python merges it in:
student = {"name": "Asha", "age": 20}
student.update({"age": 21, "city": "Pune"})
print(student)
# {'name': 'Asha', 'age': 21, 'city': 'Pune'}Notice two things happened at once. The key "age" already existed, so its value was replaced with 21, while "city" was new, so it was added. This makes update() handy for merging settings, combining form data, or joining two dictionaries. It changes the dictionary in place and returns None, so do not write student = student.update(...).
Removing keys with pop()
To remove a key and get its value back at the same time, use pop():
student = {"name": "Asha", "age": 21, "city": "Pune"}
removed = student.pop("city")
print(removed) # Pune
print(student) # {'name': 'Asha', 'age': 21}Like get(), pop() accepts a default value to avoid a KeyError when the key is missing:
print(student.pop("city", "already gone")) # already goneWithout that default, popping a missing key raises KeyError. If you only want to delete a key and do not need its value, the del statement also works, for example del student["age"].
Handling missing keys with setdefault()
setdefault() is the one beginners find confusing, but the idea is simple. It returns the value for a key if the key exists. If it does not, it first inserts the key with a default value, then returns that default.
scores = {}
# "math" is missing, so it is added with value 0
print(scores.setdefault("math", 0)) # 0
print(scores) # {'math': 0}
# "math" now exists, so its current value is returned
print(scores.setdefault("math", 999)) # 0The key point: the default is only used the first time a key is seen. After that, the existing value wins. This is perfect for building up a dictionary where each new key needs a starting value, which leads straight into our next example.
Real example: counting word frequency
Let us put these methods to work on a real task: counting how many times each word appears in a sentence. This is a classic beginner exercise and shows up in search, chat filters, and data cleaning.
text = "the cat sat on the mat the cat ran"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
# {'the': 3, 'cat': 2, 'sat': 1, 'on': 1, 'mat': 1, 'ran': 1}The trick is counts.get(word, 0). The first time we see a word, get() returns the default 0, and we add 1. Every time after that, it returns the running total. No KeyError, and no extra if checks.
You can write the same thing with setdefault() if you prefer:
counts = {}
for word in text.split():
counts.setdefault(word, 0)
counts[word] += 1Both versions give the same result. Pick whichever reads more clearly to you.
Common mistakes with Python dictionary methods
KeyError from square brackets
The most common beginner mistake is using dict[key] for a key that might not exist. Reach for get() (or setdefault()) whenever you are unsure a key is present.
Keys must be unique and hashable
Each key appears only once, so assigning to an existing key overwrites it. Keys must also be immutable types like strings, numbers, or tuples. A list cannot be used as a key.
Treating view objects like lists
The results of keys(), values(), and items() are live views, not lists. Wrap them in list() if you need to index into them or keep a fixed snapshot.
Changing a dictionary while looping over it
Adding or removing keys inside a for loop over the same dictionary can raise a RuntimeError. Loop over list(d.keys()) instead when you need to edit as you go.
Recommendation: Learn these seven methods first:
get(),keys(),values(),items(),update(),pop(), andsetdefault(). They cover the vast majority of everyday dictionary work. Practise by rewriting the word-count example from memory.
Want hands-on practice? Our free Python course walks through dictionaries, loops, and small projects step by step, so these methods become second nature.
Frequently Asked Questions
What is the difference between dict[key] and dict.get(key)?
Both read a value by its key. The difference is what happens when the key is missing: dict[key] raises a KeyError and stops your program, while dict.get(key) returns None (or a default you pass as the second argument). Use square brackets when you are certain the key exists, and get() when it might not.
How do I avoid a KeyError in Python?
Use get() to read values safely, since it returns a default instead of raising an error. For removing keys, pass a default to pop(), for example d.pop("x", None). You can also check membership first with if "x" in d:, or use setdefault() when you want to insert a starting value for missing keys.
What does setdefault() do?
setdefault(key, default) returns the value for key if it already exists. If the key is missing, it inserts the key with default and returns that default. The default is only applied the first time a key is seen, which makes it useful for building counters and grouping items.
How do I loop through a dictionary?
The clearest way is for key, value in d.items():, which gives you the key and value together on each pass. You can also loop over d.keys() for just the keys or d.values() for just the values. Looping directly over the dictionary, as in for key in d:, iterates over its keys by default.
How do I merge two dictionaries?
Call a.update(b) to merge b into a in place; keys in b overwrite matching keys in a. On Python 3.9 and later you can also create a new merged dictionary with the union operator: merged = a | b. Use update() when you want to change the original, and | when you want a fresh copy.
Are keys(), values(), and items() lists?
No. They return view objects that stay linked to the dictionary, so they update automatically when the dictionary changes. You can loop over them directly, but if you need a real list you can index into, wrap the result in list(), for example list(d.keys()).
