Chapter 10 Dictionaries

10.2 Dict Modification

There are two ways to change a dict object. The first is the setitem operation, which sets the value of a key directly via the assignment syntax, and the delitem operator, which deletes a key-value pair from a dict object. The syntax of the setitem operation is d[key] = value, where d is a dict identifier, key is an immutable object and value is an arbitrary object. If key is not an existing key in d, (key, value) is added as a new item in d. Otherwise, value is used to replace the old value of key in d. For example:

>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>> d[0] = '' # adds a new entry to d
>>> d
{1: 'a', 2: 'b', 3: 'c', 0: ''}
>>> d[1] = 'e' # update an existing entry in d
>>> d
{1: 'e', 2: 'b', 3: 'c', 0: ''}

The syntax of the delitem operation is

del d[key]

where d is a dict identifier and key is an immutable object. If key is an existing key in d, the corresponding item will be removed from d. Otherwise a key error is raised.

The del statement removes a key-value pair from a dictionary. For example, the following dictionary contains the names of various fruits and the number of each fruit in stock. If someone buys all of the pears, the entry can be removed from the dictionary.

Activity: CodeLens 1 (ten2Example1)

Dictionaries are also mutable like lists. As we’ve seen before with lists, this means that the dictionary can be modified by referencing an association on the left hand side of the assignment statement. Like before, in the previous example, instead of deleting the entry for pears, the inventory could be set to 0.

Activity: CodeLens 2 (ten2Example2)

Similarily, a new shipment of 200 bananas arriving could be handled like this.

Activity: CodeLens 3 (ten2Example3)

Notice that there are now 512 bananas—the dictionary has been modified. Note also that the len function also works on dictionaries. It returns the number of key-value pairs:

A commonly used method to change a dict object is update, which takes a single dict argument, using it to update the dict. In particular, each (key, value) pair in the argument is enumerated, and used to update the dict in the same way as setitem. If key is not already in the dict, the item (key, value) is added to the dict as a new item. Otherwise, the corresponding value of key is updated by value. The return value of the update method is None.

>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>> d1 = {0: '', 1: 'e'}
>>> d.update(d1)
>>> d
{1: 'e', 2: 'b', 3: 'c', 0: ''}

In the example above, d1 is used to update d. There are two items in d1, namely (0, ‘ ‘) and (1, ‘e’). The key 0 is not in d before the update, and therefore (0, ‘ ‘) is added to d. On the other hand, the key 1 is already in d, and therefore the existing item (1, ‘a’) in d is updated with the item (1, ‘e’).

A method to remove an item from a dict is pop, which takes a single argument. If the argument is a key in the dict, the corresponding item is removed, with is value returned. Otherwise, a key error is raised.

>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>> d.pop(1)
'a'
>>> d
{2: 'b', 3: 'c'}
>>> d.pop(0)
Traceback (most recent call last):
  File "<stdin >", line 1, in <module >
KeyError: 0

pop can take an optional second argument, which specifies the default return value if the first argument is not a key in the dict. When the second argument is given, no key error is raised.

>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>> d.pop(1, 'd')
'a'
>>> d
{2: 'b', 3: 'c'}
>>> d.pop(0, 'd')
'd'
>>> d
{2: 'b', 3: 'c'}

A method that removes all the items from a dict object is clear, which takes no argument, and returns None.

>>> d = {1: 'c', 2: 'b', 3: 'c'}
>>> d.clear()
>>> d
{}

Similar to the case of lists, modifications to a dict object shared by multiple identifiers results in a simultaneous change of values of all the identifiers.

>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>> d1 = d
>>> t1 = (d1, 4, 'd')
>>> def f(d2):
...    d2.update({0: 'e', 1: 'd'})
...    del d2 [3] ...
>>> f(t1[0])
>>> d
{1: 'd', 2: 'b', 0: 'e'}
>>> d1
{1: 'd', 2: 'b', 0: 'e'}
>>> t1
{1: 'd', 2: 'b', 0: 'e'}

In the example above, the identifiers d, d1 and t1[0] are bound to the same dict object. When f is called, the local identifier d2 is bound to the same object as the argument. As a result, when f(t1[0]) is called, all the identifiers above are changed.

Check your understanding

© Copyright 2024 GS Ng.

Next Section - 10.3 Dict Methods