Python dictionaries are mutable. If we want to add a new key-value pair, we do not need the .append
or other separate list methods. Usual assigning is enough:
d = {} # An empty dictionary
d["a"] = 100
print(d) # => {'a': 100}
d["b"] = 200
d["a"] = 0
print(d) # => {'a': 0, 'b': 200}
Here you can see that assigning a value to a new key looks the same as setting values to existing keys — it is convenient. Removing items from the dictionary is done using the pop
method. The dictionary is already more like a list in this case. Only we use the key instead of the index:
d = {'a': 1, 'b': 2}
d.pop('a') # 1
d # {'b': 2}
d.pop('BANG') # KeyError: 'BANG'
The example shows that Python will throw an exception if you try to extract a value from a non-existent key. However, we can call the pop
method with a default value. In this case, if there is no key in the dictionary, we will get this value with no exception thrown:
d = {'a': 1, 'b': 2}
d.pop('BANG', None)
d.pop('BANG', 42) # 42