Updating a dictionary

To replace the values in a dictionary with new values, use the update() method. The new key:value pairs can come from either another dictionary (or other mapping object) or an iterable of key:value pairs (such as a list of two- item tuples).

TECHNICAL The iterable (key:value) option requires Python 2.4 or later. STUFF

You can also replace values by using keyword arguments, as in this example:

>>> rooms = {'12A': 'argument clinic', 12: 'abuse'} >>> rooms.update(A14='hit on the head lessons') >>> rooms

{'12A': 'argument clinic', 12: 'abuse', 'A14': 'hit on the head lessons'}

Here's code that updates one dict by using key:value pairs from a second dict. If a key appears in both dicts, the second dict's values overwrite the first dict's values. The second dict is not modified.

>>> rooms2 = {'A14': 'canceled by Flying Fox'} >>> rooms.update(rooms2) >>> rooms

{'12A': 'argument clinic', 12: 'abuse', 'A14': 'canceled by Flying Fox'}

Was this article helpful?

0 0

Post a comment