473,378 Members | 1,411 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,378 software developers and data experts.

Check for dict key existence, and modify it in one step.

Im using this construct a lot:

if dict.has_key(whatever):
dict[whatever] += delta
else:
dict[whatever] = 1

sometimes even nested:

if dict.has_key(whatever):
if dict[whatever].has_key(someother):
dict[whatever][someother] += delta
else:
dict[whatever][someother] = 1
else:
dict[whatever]={}
dict[whatever][someother] = 1

there must be a more compact, readable and less redundant way to do
this, no?

Thanks,

Rodrigo

Aug 28 '07 #1
8 3211
rodrigo a écrit :
Im using this construct a lot:

if dict.has_key(whatever):
<ot>
Avoid using builtin names as identifiers (it shadows the builtin name).
</ot>

Unless you're using an old Python version, you'd be better using
if whatever in my_dict:
# do something here
dict[whatever] += delta
else:
dict[whatever] = 1

sometimes even nested:

if dict.has_key(whatever):
if dict[whatever].has_key(someother):
dict[whatever][someother] += delta
else:
dict[whatever][someother] = 1
else:
dict[whatever]={}
dict[whatever][someother] = 1

there must be a more compact, readable and less redundant way to do
this, no?
There are other ways, yes. With Python <= 2.4.x, you can use
dict.setdefault, with Python 2.5.x you can use a defaultdict (cf
http://docs.python.org/whatsnew/modules.html).

HTH
Aug 28 '07 #2
On Tue, 2007-08-28 at 14:36 +0000, rodrigo wrote:
Im using this construct a lot:

if dict.has_key(whatever):
dict[whatever] += delta
else:
dict[whatever] = 1
In Python 2.5 there's a defaultdict class, otherwise you can subclass
dict like this:

class CountingDictionary(dict):
def increment(self, key, delta=1):
self[key] = self.get(key, 0) + delta

Hope this helps!

--
Evan Klitzke <ev**@yelp.com>

Aug 28 '07 #3
evan,

yes, it does help. Works like it should:

class CountingDictionary(dict):
def increment(self, key, delta=1):
self[key] = self.get(key, 0) + delta

d = CountingDictionary()
d.increment('cat')
d.increment('dog',72)
print d
>>{'dog': 72, 'cat': 1}
Thanks!

Aug 28 '07 #4
You're right of course, I was unclear. I wasn't using 'dict' to
override the dict clas, but just as a standin for the example (the
actual dictionary names are varied).

Thanks,

Rodriog

Aug 28 '07 #5
rodrigo <ro********@gmail.comwrites:
Im using this construct a lot:

if dict.has_key(whatever):
dict[whatever] += delta
else:
dict[whatever] = 1
I'd prefer:

foo.setdefault(whatever, 0)
foo[whatever] += delta
sometimes even nested:

if dict.has_key(whatever):
if dict[whatever].has_key(someother):
dict[whatever][someother] += delta
else:
dict[whatever][someother] = 1
else:
dict[whatever]={}
dict[whatever][someother] = 1
foo.setdefault(whatever, {})
foo[whatever].setdefault(someother, 0)
foo[whatever] += delta
there must be a more compact, readable and less redundant way to do
this, no?
Hope that helps.

--
\ "I took a course in speed waiting. Now I can wait an hour in |
`\ only ten minutes." -- Steven Wright |
_o__) |
Ben Finney
Aug 28 '07 #6
Ben Finney <bi****************@benfinney.id.auwrites:
foo.setdefault(whatever, {})
foo[whatever].setdefault(someother, 0)
foo[whatever] += delta
Should, of course, be:

foo.setdefault(whatever, {})
foo[whatever].setdefault(someother, 0)
foo[whatever][someother] += delta

--
\ "My house is made out of balsa wood, so when I want to scare |
`\ the neighborhood kids I lift it over my head and tell them to |
_o__) get out of my yard or I'll throw it at them." -- Steven Wright |
Ben Finney
Aug 28 '07 #7
On Aug 28, 1:13 pm, rodrigo <rodrigo...@gmail.comwrote:
evan,

yes, it does help. Works like it should:

class CountingDictionary(dict):
def increment(self, key, delta=1):
self[key] = self.get(key, 0) + delta

d = CountingDictionary()
d.increment('cat')
d.increment('dog',72)
print d
>{'dog': 72, 'cat': 1}

Thanks!
You responded to the answer that made the least use of already
existing recourses in python. Just letting you know.

Aug 29 '07 #8
rodrigo a écrit :
You're right of course, I was unclear. I wasn't using 'dict' to
override the dict clas, but just as a standin for the example (the
actual dictionary names are varied).
I guessed so, but Python's behaviour wrt/ naming can be somewhat
surprising for newcomers, and accidentally shadowing builtins (or not
builtins FWIW) names is a common pitfall. So better to warn newcomers
lurking here !-)
Aug 29 '07 #9

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

Similar topics

5
by: Richard A. DeVenezia | last post by:
Dear Experts: Suppose I have global variables: x1, x2, x3 and I have a function that needs to assign a value to a new global variable x4 something like function foo () { count = 0;
0
by: barnesc | last post by:
Nifty, Tim Peters responded to my e-mail. I must've said something interesting. Cool, a PyCelebrity! > >> ... >> I've gotten bored and went back to one of my other projects: >>...
11
by: sandravandale | last post by:
I can think of several messy ways of making a dict that sets a flag if it's been altered, but I have a hunch that experienced python programmers would probably have an easier (well maybe more...
1
by: jslowery | last post by:
Hmm, I know this is something fundamental about how Python implements predicate dispatch, but for some reason I believed that this would work: class delegate_dict(dict): def __init__(self,...
25
by: Michele Petrazzo | last post by:
Hi ng, what the preferred way for see if the dict has a key? We have a lot of solutions: key in dict key in dict.keys() dict.has_key(key) .... but what the better or the more "pythonic"?
25
by: pamelafluente | last post by:
Hi Guys, I have the following HTML code which is doing a GET to a page, say MyUrl.aspx : <body> <form name="form1" method="get" action="MyUrl.aspx" id="form1"> <input type="hidden"...
16
by: chosechu | last post by:
Hello Pythoneers: I need to pass a list of named arguments to a function in a given order, and make sure these named arguments are retrieved using keys() in the same order they were given....
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...
10
by: Dieter Pelz | last post by:
Hallo, what is the best way to check the installation of mfc80 and vcrt sidebyside assemblies? Best Regards, Dieter Pelz
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
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...

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.