dict.update() useful or not?
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Mon Aug 11 13:18:20 EDT 2008
dict1.update(dict2) is of course equivalent to this code:
for key, value in dict2.iteritems():
dict1[key] = value
Note that it replaces values in dict1 with the value taken from dict2. I
don't know about other people, but I more often want to keep the values
in dict1 regardless of what's in dict2, and only add items from dict2 if
it is new key. Like this:
for key, value in dict2.iteritems():
if not dict1.has_key(key):
dict1[key] = value
Here's some code modified from something I wrote the other day:
import urllib2
def create_request(url, headers):
tmp = DEFAULT_HEADERS.copy()
tmp.update(headers)
req = urllib2.Request(url, None, tmp)
# ...
return req
There's the faintest of code smells to me. I would prefer to write
something like this:
def create_request(url, headers):
headers.update(DEFAULT_HEADERS)
req = urllib2.Request(url, None, headers)
# ...
return req
but of course this second example does the Wrong Thing, replacing
explicit headers with default values.
What do other people find? Do you find use for dict.update()? What other
idioms do you use for combining dictionaries?
--
Steven
More information about the Python-list
mailing list