Python Arena
Step 5 of 6

Removing keys

del removes a key and its value from a dictionary:

lockers = {"Ada": 12, "Max": 7, "Lin": 3}
del lockers["Max"]
print(lockers)
Output
{'Ada': 12, 'Lin': 3}

Removing a key that isn't there stops the program with a KeyError, just like reading one. When you aren't sure the key is there, check with in first:

lockers = {"Ada": 12, "Lin": 3}
name = "Max"
if name in lockers:
    del lockers[name]
    print(name, "gave back the key")
else:
    print(name, "has no locker")
Output
Max has no locker

pop

The method pop removes a key too, and it returns the key's value, which is handy when you still need it:

In the Python interpreter
>>> lockers = {"Ada": 12, "Lin": 3}
>>> freed = lockers.pop("Ada")
>>> freed
12
>>> lockers
{'Lin': 3}
>>> print(lockers.pop("Max", None))
None

Given a second argument, pop doesn't stop at a missing key: it returns the second argument instead. None, Python's "no value", is a common choice. To check whether a value is None, write is None:

lockers = {"Ada": 12, "Lin": 3}
freed = lockers.pop("Max", None)
if freed is None:
    print("Max has no locker")
else:
    print("Locker", freed, "is free")
Output
Max has no locker

Not while looping over it

Removing keys inside a for loop over the same dictionary stops the program:

stock = {"apples": 5, "pears": 0, "plums": 0}
for fruit in stock:
    if stock[fruit] == 0:
        del stock[fruit]
Python stops with
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    for fruit in stock:
                 ^^^^^
RuntimeError: dictionary changed size during iteration

The loop can't keep its place in a dictionary that changes size under it. Loop over a list of the keys instead. list(stock) makes one, and that list stays as it is when the dictionary changes:

stock = {"apples": 5, "pears": 0, "plums": 0}
for fruit in list(stock):
    if stock[fruit] == 0:
        del stock[fruit]
print(stock)
Output
{'apples': 5}

To empty a whole dictionary in one go, use the method clear(): stock.clear().

Like a list, a dictionary given to a function is passed as a reference. A function can add, change and remove the keys of the caller's dictionary.

Your task

Challenge 1 of 3

What does this program print? Type each line it prints.

Challenge 2

Write a function remove_below(scores, limit) that removes from the dictionary it's given every name whose score is below limit. It changes the dictionary and returns nothing.

scores = {"Ada": 9, "Max": 4, "Lin": 6, "Kim": 2}
remove_below(scores, 5)
print(scores)
{'Ada': 9, 'Lin': 6}

Challenge 3

Write a function rename_key(data, old, new) that moves the value of the key old to the key new in the dictionary it's given, so that old is no longer a key. If old isn't in the dictionary, the function changes nothing. It returns nothing.

ages = {"Ada": 36, "Max": 41}
rename_key(ages, "Max", "Maxine")
print(ages)
{'Ada': 36, 'Maxine': 41}