dict.update() useful or not?

S

Steven D'Aprano

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

Martin v. Löwis

def create_request(url, headers):
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?

Just in case it isn't clear what the problem with that code is:
create_request is a function, ie. it returns a value. As such,
it shouldn't have any side effects. If it has side effects, it
should be considered a procedure, and return None.

Regards,
Martin
 
A

Aahz

What do other people find? Do you find use for dict.update()? What other
idioms do you use for combining dictionaries?

My company's code relies heavily on d.update() -- it's extremely handy in
the context of a web form.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,265
Latest member
TodLarocca

Latest Threads

Top