Removing keys
del removes a key and its value from a dictionary:
lockers = {"Ada": 12, "Max": 7, "Lin": 3}
del lockers["Max"]
print(lockers)
{'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")
Max has no lockerpop
The method pop removes a key too, and it returns the key's value, which is handy when you still need it:
>>> lockers = {"Ada": 12, "Lin": 3}
>>> freed = lockers.pop("Ada")
>>> freed
12
>>> lockers
{'Lin': 3}
>>> print(lockers.pop("Max", None))
NoneGiven 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")
Max has no lockerNot 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]
Traceback (most recent call last):
File "main.py", line 2, in <module>
for fruit in stock:
^^^^^
RuntimeError: dictionary changed size during iterationThe 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)
{'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.