Python Dictionary Operations
Table of Contents + −
In the last lesson you learned Introduction to Dictionaries. You saw what a dictionary is and how to build one. Now comes the part you will actually do every day. You will work with the data inside it. You will read a value, add a new pair, change one, and remove one. You will also ask simple questions. Is this key here? How many pairs do I have?
🤔 Why You Need Dictionary Operations
Picture a small app that stores one user’s profile. You have a dictionary with their name, age, and city. Real apps never just sit still. The user edits their city. Later you add a phone number. Someone deletes a field. If you do not know how to read, change, and remove items by key, that dictionary is frozen and useless.
The fix is simple. Python gives you a small set of everyday operations for exactly this. Once you know them, a dictionary becomes a live thing. You can update it as your program runs.
Here is the running example we will use the whole way through. It is one user’s profile.
user = { "name": "Riya", "age": 28, "city": "Mumbai",}print(user)Output
{'name': 'Riya', 'age': 28, 'city': 'Mumbai'}Think of this like a labelled drawer. Each label is the key. It points to one thing inside, which is the value. Everything below is just opening a drawer by its label and doing something with what is inside.
🔑 Read a Value by Its Key
To get a value out, you write the dictionary name and then the key in square brackets. The key is the label. Python hands you back what is stored under it.
print(user["name"])print(user["age"])Output
Riya28So user["name"] means “look in user, find the label name, give me its value.” That is the most common thing you will ever do with a dictionary.
There is one catch. If you ask for a key that is not there, Python does not stay quiet. It stops the program with an error called a KeyError.
print(user["email"])Output
Traceback (most recent call last): File "main.py", line 1, in <module> print(user["email"]) ~~~~^^^^^^^^^KeyError: 'email'A KeyError just means you asked for a label that does not exist in this drawer. We will see a safe way to check first in a moment.
➕ Add a New Pair
Adding uses the same square-bracket idea. But now you put it on the left of an = sign. If the key does not exist yet, Python creates it.
user["email"] = "riya@example.com"print(user)Output
{'name': 'Riya', 'age': 28, 'city': 'Mumbai', 'email': 'riya@example.com'}See what happened? There was no email before. So Python added a brand new pair at the end. You do not need a special “add” command. You just assign to a new key and it appears.
✏️ Update an Existing Value
Now here is the neat thing. Updating uses the exact same line as adding. The only difference is whether the key already exists.
If the key is already there, the old value gets replaced. If it is not there, a new pair is created. Python decides for you based on the key.
user["city"] = "Bengaluru"print(user)Output
{'name': 'Riya', 'age': 28, 'city': 'Bengaluru', 'email': 'riya@example.com'}The city key already held "Mumbai". So the new value "Bengaluru" simply took its place. The pair did not move and no duplicate was made. A key can only point to one value at a time. So the old one is gone.
Tip
Both adding and updating use dict[key] = value. Whether it adds or replaces depends only on whether that key already exists. You do not pick. The key does.
❓ Check if a Key Exists with in
Remember that KeyError from before? You avoid it by asking first. The in keyword checks whether a key is present. It gives you back True or False.
print("email" in user)print("phone" in user)Output
TrueFalseThis is perfect inside an if. Check before you read, and you will never hit that error.
if "city" in user: print(f"City is {user['city']}")else: print("No city on file")Output
City is BengaluruNow one thing trips up a lot of people, so read this slowly. The in keyword checks the keys, not the values. So "city" in user is True. But "Bengaluru" in user is False, even though Bengaluru really is in there as a value.
print("city" in user) # checking a keyprint("Bengaluru" in user) # checking a valueOutput
TrueFalseSo just remember. The in keyword asks “is this a label?”, not “is this stored somewhere inside?”.
🗑️ Delete a Pair with del or pop()
Sometimes you need to remove a pair completely. There are two common ways. They are good for different moments.
The first is del. You point it at one key and that pair is gone.
del user["email"]print(user)Output
{'name': 'Riya', 'age': 28, 'city': 'Bengaluru'}The email pair is removed entirely, both the label and the value. Note that del does not give you the value back. It just deletes.
The second way is pop(). It removes the pair too. But it also returns the value it removed. So you can use the value one last time as you take it out.
removed_age = user.pop("age")print(removed_age)print(user)Output
28{'name': 'Riya', 'city': 'Bengaluru'}Here pop("age") pulled the value 28 out. It handed it to us so we could store it in removed_age. Then it removed the pair. Think of del as “throw it away” and pop() as “take it out and keep it in my hand.”
Both del and pop() raise a KeyError if the key is not there. But pop() has a friendly option. Pass a second value. It gives you that instead of crashing when the key is missing.
phone = user.pop("phone", "not set")print(phone)Output
not setThere was no phone key. So pop() did not error. It just returned our fallback "not set". That second argument is a small thing that saves you from a lot of crashes.
Caution
del user["phone"] with a missing key will crash with a KeyError. There is no fallback option for del. If the key might be missing, check with in first, or use pop() with a default value.
🔢 Count Pairs with len()
Last one, and it is easy. To find out how many pairs a dictionary holds, wrap it in len(). It counts pairs. Each key-and-value together counts as one.
print(len(user))Output
2Our user has two pairs left right now, name and city. So len() returns 2. An empty dictionary {} would give 0. This is handy when you want to ask “do I have anything stored yet?” before you start looping over it.
Here is a quick table of everything we just covered, so you have it in one place.
| Operation | How you write it | What it does |
|---|---|---|
| Read | user["name"] | Gives the value for that key |
| Add | user["email"] = "..." | Creates a new pair if the key is new |
| Update | user["city"] = "..." | Replaces the value if the key exists |
| Check key | "name" in user | Returns True or False for a key |
| Delete | del user["age"] | Removes the pair, returns nothing |
| Remove and keep | user.pop("age") | Removes the pair and returns its value |
| Count | len(user) | Returns how many pairs there are |
⚠️ Common Mistakes
A few slips catch almost everyone the first time. Watch for these.
- Reading a key that does not exist crashes the program. Check with
infirst, or usepop()/.get()with a default.
# ❌ Avoid: crashes if "email" is not a keyemail = user["email"]
# ✅ Good: check firstif "email" in user: email = user["email"]- Thinking
inchecks values. It checks keys only.
# ❌ Avoid: this is False even though Bengaluru is a valueprint("Bengaluru" in user)
# ✅ Good: check the keyprint("city" in user)- Using
delon a key that might be missing. It crashes with no fallback.
# ❌ Avoid: KeyError if "phone" is not theredel user["phone"]
# ✅ Good: pop with a default never crashesuser.pop("phone", None)- Expecting
delto give you the value back. It does not. Usepop()when you need the value as you remove it.
✅ Best Practices
- Use
into check before reading a key you are not sure about. It is the simplest guard againstKeyError. - Reach for
pop("key", default)when a key might be missing. The default turns a crash into a calm fallback. - Pick
delwhen you just want a pair gone, andpop()when you also need its value. - Keep your keys consistent. If you store
"email", always read"email", not"Email"or"e-mail". Keys are case-sensitive and exact.
🧩 What You’ve Learned
✅ Read a value with dict[key], and a missing key raises a KeyError.
✅ Add a new pair and update an existing one with the same dict[key] = value line. The key decides which happens.
✅ Check whether a key exists with in, and in looks at keys, not values.
✅ Remove a pair with del (just deletes) or pop() (deletes and returns the value, with an optional default).
✅ Count how many pairs a dictionary holds with len().
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does user["role"] = "admin" do if user has no "role" key yet?
Why: Assigning to a key that does not exist creates a brand new pair; the same line updates the value when the key already exists.
- 2
Given user = {"city": "Mumbai"}, what does "Mumbai" in user return?
Why: The in keyword checks the keys only, so "Mumbai" (a value) is not found and it returns False.
- 3
What is the main difference between del user["age"] and user.pop("age")?
Why: Both remove the pair, but pop() also hands back the value it removed, while del simply deletes it.
- 4
How do you safely remove "phone" when it might not be a key, without crashing?
Why: pop() with a default value returns the default instead of raising a KeyError when the key is missing.
🚀 What’s Next?
You can now do all the basic moves on a dictionary by hand. Next we will meet the built-in methods that make some of these jobs even shorter and add a few new tricks.