Update existing Dictonaries

You can update a dictionary by adding a new entry or element (i.e., a key-value pair), modifying an existing entry, or deleting an existing entry (see below for more details on removing an entry).


>>> dict2 = {'name':'earth','port':80}
>>> dict2['name'] = 'venus'
>>> dict2['port'] = 6969
>>> dict2['arch'] = 'sonic'
>>> dict2
{'arch': 'sonic', 'name': 'venus', 'port': 6969}
>>> print 'host %(name)s is running on port %(port)d' % dict2
host venus is running on port 6969

If the key does exist, then its previous value will be overridden by its new value. The print statement above illustrates an alternative way of using the string format operator ( % ), specific to dictionaries. Using the dictionary argument, you can shorten the print request somewhat because naming of the dictionary occurs only once, as opposed to occurring for each element using a tuple argument.
You may also add the contents of an entire dictionary to another dictionary by using the update() built-in method.


You may also like...