473,386 Members | 1,652 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

dict.update() useful or not?

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
Aug 11 '08 #1
3 1909
Steven D'Aprano <st***@REMOVE-THIS-cybersource.com.auwrote:
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
Aug 11 '08 #2
>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?
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
Aug 11 '08 #3
In article <00**********************@news.astraweb.com>,
Steven D'Aprano <st***@REMOVE-THIS-cybersource.com.auwrote:
>
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.
--
Aahz (aa**@pythoncraft.com) <* http://www.pythoncraft.com/

Adopt A Process -- stop killing all your children!
Aug 13 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Robin Cull | last post by:
Imagine I have a dict looking something like this: myDict = {"key 1": , "key 2": , "key 3": , "key 4": } That is, a set of keys which have a variable length list of associated values after...
4
by: Steven Bethard | last post by:
I'd like to subclass dict to disallow overwriting of keys, something like: >>> class SafeDict(dict): .... def __setitem__(self, key, value): .... if key in self: .... raise...
6
by: Rick Morrison | last post by:
Would there be any way to add a method to all dict objects that operated like the .update() method, but also returned a reference to the updated dict? ..update() is clumsy to use inside of list...
8
by: bearophileHUGS | last post by:
I'm frequently using Py2.4 sets, I find them quite useful, and I like them, even if they seem a little slower than dicts. Sets also need the same memory of dicts (can they be made to use less...
11
by: Ville Vainio | last post by:
I need a dict (well, it would be optimal anyway) class that stores the keys as strings without coercing the case to upper or lower, but still provides fast lookup (i.e. uses hash table). >> d...
2
by: Alex | last post by:
Entering >>> help(dict) Help on class dict in module __builtin__: class dict(object) | dict() -> new empty dictionary. | dict(mapping) -> new dictionary initialized from a mapping object's...
4
by: bearophileHUGS | last post by:
I have started doing practice creating C extensions for CPython, so here are two ideas I have had, possibly useless. If you keep adding elements to a CPython dict/set, it periodically rebuilds...
8
by: Almad | last post by:
Hello, I discovered this behaviour in dictionary which I find confusing. In SneakyLang, I've tried to extend dictionary so it visits another class after something is added: class...
20
by: Pat | last post by:
I know it's not "fair" to compare language features, but it seems to me (a Python newbie) that appending a new key/value to a dict in Python is awfully cumbersome. In Python, this is the best...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.