Modifying Python Dictionaries
Introduction
Welcome back to Organizing Data with Dictionaries in Python! We are now in the second unit of four, and it is time to put our dictionaries in motion.
In the previous unit, we built a user profile and read data from it. Notice, though, that the dictionary itself never changed: we only ever looked inside. Real records rarely sit still. A product gets restocked, a price drops during a sale, and a field that once mattered becomes obsolete and needs to go. Just like lists, dictionaries are mutable, which means we can reshape them after creation without building a brand-new one.
In this lesson, we will work with four tools:
- Assignment to add a brand-new key-value pair;
- Assignment again to overwrite the value of a key that already exists;
- The
update()method to apply several changes at once; pop()anddelto remove entries.
Our running example will be a small product record for a notebook sold in a stationery shop. By the end, we will have grown it, edited it, and trimmed it back down.
Adding a New Entry with Assignment
Let us start with a minimal product record holding just two pieces of information, then give it a third. Adding an entry requires no special method at all: we simply assign a value to a key that does not exist yet.
This one line is worth pausing over because it behaves differently from what we saw with lists:
- With a list, assigning to a position that does not exist (
items[7] = "x"on a short list) raises anIndexError, since there is no slot to write into. - With a dictionary, there are no numbered slots. If the key
"stock"is absent, Python creates the pair on the spot.
That is why dictionaries need no append()-style method: assignment covers both jobs. The new pair lands at the end of the dictionary's order, so product now holds "name", "price", and "stock" in that sequence.
Overwriting an Existing Value with Assignment
Now suppose the notebook goes on sale. We want the "price" key to hold a new number, and the syntax is exactly the same as before.
The bracket-assignment syntax quietly does one of two jobs, depending on the dictionary's current contents: it creates the pair when the key is missing and replaces the value when the key is already there. Since "price" exists, the old 5.00 is gone, and no error or warning tells us so. Notice also that overwriting does not move the key: "price" stays in its original position.
If we ever need to be careful not to clobber existing data, the in check from the previous unit is our guard: we can test if "price" not in product before writing.
Setting Several Entries at Once with update()
Changing entries one line at a time is fine for a single edit, but when several fields change together, the update() method lets us pass them all in one dictionary.
update() applies the same create-or-replace rule to every pair it receives:
"price"already exists, so its value is replaced with4.25."category"does not exist, so it is added as a new pair at the end.
One detail is easy to trip over: update() modifies the dictionary in place and returns None, much like the list methods we met earlier in the course. So we call it as a statement and never write product = product.update(...), which would throw our data away and leave product set to None.
Removing an Entry and Keeping Its Value with pop()
Our shop no longer tracks stock in this record, but before dropping the field, we would like to know the final count. That is precisely what pop() is for: it removes the entry and hands the value back to us.
As you may recall from the lists course, pop() follows the same "remove and hand it back" idea; the difference is that a dictionary's pop() takes a key, not an index. The variable removed now holds 120, and "stock" is no longer part of product.
Two more points about missing keys: calling pop() with a key that is not present raises a KeyError, and passing a second argument supplies a fallback instead, exactly as get() does. For example, product.pop("color", "unknown") returns "unknown" without complaining.
Removing an Entry with del
Sometimes we truly do not care about the value being discarded; we just want the key gone. For that, Python gives us the del statement.
Here, "category" is deleted outright, and its value, "stationery", simply disappears with no way to recover it. Notice the shape of the line: del is a statement written before the target, not a method called on the dictionary, so there is nothing to assign from it.
This table sums up how the two removal tools compare so we can pick the right one:
| Feature | pop() | del |
|---|---|---|
| Syntax | product.pop("stock") | del product["stock"] |
| Kind | Method | Statement |
| Return value | The removed value | Nothing to capture |
| Missing key | KeyError, unless a default is given | KeyError, no default possible |
Putting It All Together
Let us view the full script in one place and watch a single dictionary travel through every operation we have covered.
The record starts with two entries, grows to three when "stock" is added, has its price rewritten, and then reaches four entries after update() replaces "price" and appends "category". The two removals bring it back down to "name" and "price".
Conclusion and Next Steps
Excellent work: our dictionaries are no longer read-only. We now know that bracket assignment does double duty, creating a pair when the key is new and replacing the value when the key already exists, and that update() extends that same rule to a whole batch of pairs in one in-place call. On the removal side, we have two flavors to choose from: pop() when we still need the value that is leaving and del when the entry can simply disappear. We also saw that both removal tools raise a KeyError for keys that are not there and that only pop() accepts a default to soften the blow.
The practices ahead hand the keyboard over to you: you will add a fresh key to a product record, overwrite an existing value and confirm the change, push several edits through update(), then remove one entry with pop() while capturing its value and clear another with del. In the next unit, we will step back and iterate over dictionaries, walking through keys, values, and pairs to summarize and filter entries. Time to reshape some records of your own!
