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
Another version of pop
without arguments is the popitem
method. It extracts the key and value as a tuple, and if the dictionary is already empty, it throws an exception:
d = {'a': 1}
d.popitem() # ('a', 1)
d.popitem() # KeyError: 'popitem(): dictionary is empty'
Remember that the order of keys in the dictionary does not depend on the order in which we added these keys to the dictionary. Therefore, we cannot rely on the order in which Python returns data when we call popitem
. But we can be sure we extracted everything and did it only once for all pairs.
Adding one dictionary to another
Lists have the extend
method that extends one list with another. Dictionaries have a similar update
method. However, the associated dictionary object does not just get key-value pairs from the new dictionary when we call update
.
There is an actual data update hence update
. We added new keys to the dictionary, and if some keys already existed before, we will replace the values associated with them with new ones, for example:
cart = {'apples': 2, 'oranges': 1}
addon = {'oranges': 5, 'lemons': 3}
cart.update(addon)
cart # {'apples': 2, 'oranges': 5, 'lemons': 3}
We added lemons and updated the number of oranges — it is clear, simple, and convenient.
Copying a dictionary
In the case of lists, we can add together two lists and get a new one. Or we can get a copy of one list and append it with data from the second, but we cannot combine dictionaries, and they do not support slices, either.
However, they have the copy
method, which works similarly to copying a list using a [:]
slice. When we call it, it returns a so-called shallow copy of the dictionary. The shallow copy only reproduces the structure of the dictionary. It does not copy the values but creates new links to them. Nevertheless, the shallow copy is a new dictionary that can change its composition without affecting the original:
d = {'a': 1, 'b': [42]}
c = d.copy()
c.update({'a': 10, '1k': 1024})
c # {'a': 10, 'b': [42], '1k': 1024}
c['b'].append(None)
c # {'a': 10, 'b': [42, None], '1k': 1024}
d # {'a': 1, 'b': [42, None]}
The c
dictionary got its structure, and its update did not affect the original d
dictionary. We replicated the link to the list when we copied the dictionary, so changing the list object by reference affected the original list too.
Clearing a dictionary
We can clear lists by assigning a l[:] = []
slice using the clear
method with dictionaries:
d = {'a': 1}
d.clear()
d # {}
The clear()
method removes all elements from the current dictionary.
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.