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:

  1. Assignment to add a brand-new key-value pair;
  2. Assignment again to overwrite the value of a key that already exists;
  3. The update() method to apply several changes at once;
  4. pop() and del to 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.

Python
product = {"name": "Notebook", "price": 5.00}

# Assigning a new key adds an entry
product["stock"] = 120

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 an IndexError, 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.

Python
# Assigning an existing key overwrites its value
product["price"] = 4.50
print("After adding/updating:", product)

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.

text
After adding/updating: {'name': 'Notebook', 'price': 4.5, 'stock': 120}

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.

Python
# update() sets several entries at once
product.update({"price": 4.25, "category": "stationery"})
print("After update():", product)

update() applies the same create-or-replace rule to every pair it receives:

  • "price" already exists, so its value is replaced with 4.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.

text
After update(): {'name': 'Notebook', 'price': 4.25, 'stock': 120, 'category': 'stationery'}

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.

Python
# pop() removes by key and returns the value
removed = product.pop("stock")
print("Removed stock:", removed)

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.

text
Removed stock: 120

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.

Python
# del removes an entry by key
del product["category"]
print("Final product:", product)

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.

text
Final product: {'name': 'Notebook', 'price': 4.25}

This table sums up how the two removal tools compare so we can pick the right one:

Featurepop()del
Syntaxproduct.pop("stock")del product["stock"]
KindMethodStatement
Return valueThe removed valueNothing to capture
Missing keyKeyError, unless a default is givenKeyError, 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.

Python
product = {"name": "Notebook", "price": 5.00}

# Assigning a new key adds an entry
product["stock"] = 120

# Assigning an existing key overwrites its value
product["price"] = 4.50
print("After adding/updating:", product)

# update() sets several entries at once
product.update({"price": 4.25, "category": "stationery"})
print("After update():", product)

# pop() removes by key and returns the value
removed = product.pop("stock")
print("Removed stock:", removed)

# del removes an entry by key
del product["category"]
print("Final product:", product)

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".

text
After adding/updating: {'name': 'Notebook', 'price': 4.5, 'stock': 120}
After update(): {'name': 'Notebook', 'price': 4.25, 'stock': 120, 'category': 'stationery'}
Removed stock: 120
Final product: {'name': 'Notebook', 'price': 4.25}

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!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal