dict.update() useful or not?

Duncan Booth duncan.booth at invalid.invalid
Mon Aug 11 13:53:19 EDT 2008


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:

> 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
> 

If you don't actually need to mutate dict1 in-place then just use update 
for this:

    	d = dict(dict2)
    	d.update(dict1)
    	dict1 = d

> 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.

There's a second code smell with that: even if it did what you want it 
isn't nice to mutate the parameter passed in as headers. What if the caller 
wants to reuse the headers again for another call? Much nicer just to do:

def create_request(url, headers):
    hdrs = dict(DEFAULT_HEADERS)
    hdrs.update(headers)
    req = urllib2.Request(url, None, hdrs)
    # ... 
    return req



More information about the Python-list mailing list