473,765 Members | 2,010 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pythonic way for missing dict keys

Hi all!

I am pretty sure this has been asked a couple of times, but I don't seem
to find it on the archives (Google seems to have a couple of problems
lately).

I am wondering what is the most pythonic way of dealing with missing
keys and default values.

According to my readings one can take the following approaches:

1/ check before (this has a specific name and acronym that I haven't
learnt yet by heart)

if not my_dict.has_key (key):
my_obj = myobject()
my_dict[key] = my_obj
else:
my_obj = my_dict[key]

2/ try and react on error (this has also a specific name, but...)

try:
my_obj = my_dict[key]
except AttributeError:
my_obj = myobject()
my_dict[key] = my_obj

3/ dict.get usage:

my_obj = my_dict.get(key , myobject())

I am wondering which one is the most recommended way? get usage seems
the clearest, but the only problem I see is that I think myobject() is
evaluated at call time, and so if the initialization is expensive you
will probably see surprises.

thanks in advance,
../alex
--
..w( the_mindstorm )p.

Jul 20 '07 #1
25 4693
On 2007-07-20, Alex Popescu <th************ ***********@gma il.comwrote:
Hi all!

I am pretty sure this has been asked a couple of times, but I
don't seem to find it on the archives (Google seems to have a
couple of problems lately).

I am wondering what is the most pythonic way of dealing with missing
keys and default values.

According to my readings one can take the following approaches:
There's also the popular collections.def aultdict.

Usually, the get method of normal dicts is what I want. I use a
defaultdict only when the implicit addition to the dictionary of
defaulted elements is what I really want.

--
Neil Cerutti
Jul 20 '07 #2
Neil Cerutti <ho*****@yahoo. comwrote in
news:sl******** ***********@FIA D06.norwich.edu :
On 2007-07-20, Alex Popescu <th************ ***********@gma il.comwrote:
>Hi all!

I am pretty sure this has been asked a couple of times, but I
don't seem to find it on the archives (Google seems to have a
couple of problems lately).

I am wondering what is the most pythonic way of dealing with missing
keys and default values.

According to my readings one can take the following approaches:

There's also the popular collections.def aultdict.

Usually, the get method of normal dicts is what I want. I use a
defaultdict only when the implicit addition to the dictionary of
defaulted elements is what I really want.
This looks like the closest to my needs, but in my case the default value
involves the creation of a custom object instance that is taking parameters
from the current execution context, so I am not very sure I can use it.

../alex
--
..w( the_mindstorm )p.

Jul 20 '07 #3
Version 1 and 2 do different thing than version 3. The latter doesn't
add value to dict.

As it was mentioned before, use:
1 - if you expect that there's no key in dict
2 - if you expect that there is key in dict

Jul 20 '07 #4
Jakub Stolarski <ja************ *@gmail.comwrot e in
news:11******** **************@ k79g2000hse.goo glegroups.com:
Version 1 and 2 do different thing than version 3. The latter doesn't
add value to dict.

As it was mentioned before, use:
1 - if you expect that there's no key in dict
2 - if you expect that there is key in dict
I may be missing something but I think the 3 approaches are completely
equivalent in terms of functionality.

../alex
--
..w( the_mindstorm )p.

Jul 20 '07 #5
On Fri, 2007-07-20 at 19:39 +0000, Alex Popescu wrote:
Neil Cerutti <ho*****@yahoo. comwrote in
news:sl******** ***********@FIA D06.norwich.edu :
On 2007-07-20, Alex Popescu <th************ ***********@gma il.comwrote:
Hi all!

I am pretty sure this has been asked a couple of times, but I
don't seem to find it on the archives (Google seems to have a
couple of problems lately).

I am wondering what is the most pythonic way of dealing with missing
keys and default values.

According to my readings one can take the following approaches:
There's also the popular collections.def aultdict.

Usually, the get method of normal dicts is what I want. I use a
defaultdict only when the implicit addition to the dictionary of
defaulted elements is what I really want.

This looks like the closest to my needs, but in my case the default value
involves the creation of a custom object instance that is taking parameters
from the current execution context, so I am not very sure I can use it.
If by "current execution context" you mean globally visible names, this
should still be possible:
>>from collections import defaultdict
def make_default():
.... return x+y
....
>>dd = defaultdict(mak e_default)
x = 40
y = 2
print dd[0]
42
>>x = "Dead"
y = " Parrot"
print dd[1]
Dead Parrot
>>print dd
defaultdict(<fu nction make_default at 0xb7f71e2c>, {0: 42, 1: 'Dead Parrot'})

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
Jul 20 '07 #6
On Fri, 20 Jul 2007 19:08:57 +0000, Alex Popescu wrote:
I am wondering what is the most pythonic way of dealing with missing
keys and default values.
[snip three versions]

Others have already mentioned the collections.def aultdict type, however it
seems people have forgotten about the setdefault method of dictionaries.

value = somedict.setdef ault(key, defaultvalue)

The disadvantage of setdefault is that the defaultvalue has to be created
up front. The disadvantage of collections.def aultdict is that the "default
factory" function takes no arguments, which makes it rather less than
convenient. One can work around this using global variables:

# The default value is expensive to calculate, and known
# only at runtime.
>>expensivefunc tion = lambda x: str(x)
D = collections.def aultdict(lambda : expensivefuncti on(context))
# lots of code goes here...

# set context just before fetching from the default dict
>>context = 42
value = D['key']
print value, D
42 defaultdict(<fu nction <lambdaat 0xb7eb4fb4>, {'key': '42'})

but one should be very leery of relying on global variables like that.

That suggests the best solution is something like this:

def getdefault(adic t, key, expensivefuncti on, context):
if key in adict:
return adict[key]
else:
value = expensivefuncti on(context)
adict[key] = value
return value

--
Steven.

Jul 21 '07 #7
Can someone who knows about python internals throw some light on why
>>x in dic
is cheaper than
>>dic.has_key(x )
??
Jul 21 '07 #8
On Sat, 21 Jul 2007 09:22:32 +0530, Rustom Mody wrote
Can someone who knows about python internals throw some light on why
>x in dic
is cheaper than
>dic.has_key( x)

??
I won't claim to know Python internals, but compiling and disassembling the
expressions in question reveals the reason:
>>from compiler import compile
from dis import dis
dis(compile(" dic.has_key(x)" ,"","eval"))
1 0 LOAD_NAME 0 (dic)
3 LOAD_ATTR 1 (has_key)
6 LOAD_NAME 2 (x)
9 CALL_FUNCTION 1
12 RETURN_VALUE
>>dis(compile(" x in dic","","eval") )
1 0 LOAD_NAME 0 (x)
3 LOAD_NAME 1 (dic)
6 COMPARE_OP 6 (in)
9 RETURN_VALUE

"dic.has_key(x) " goes through an attribute lookup to find the function that
looks for the key. "x in dic" finds the function more directly.

--
Carsten Haese
http://informixdb.sourceforge.net

Jul 21 '07 #9
Alex Popescu a écrit :
Hi all!

I am pretty sure this has been asked a couple of times, but I don't seem
to find it on the archives (Google seems to have a couple of problems
lately).

I am wondering what is the most pythonic way of dealing with missing
keys and default values.

According to my readings one can take the following approaches:

1/ check before (this has a specific name and acronym that I haven't
learnt yet by heart)

if not my_dict.has_key (key):
my_obj = myobject()
my_dict[key] = my_obj
else:
my_obj = my_dict[key]
if key not in my_dict:
my_obj = my_dict[key] = myobject()
else:
my_obj = my_dict[key]
2/ try and react on error (this has also a specific name, but...)

try:
my_obj = my_dict[key]
except AttributeError:
my_obj = myobject()
my_dict[key] = my_obj
cf above for a shortcut...
3/ dict.get usage:

my_obj = my_dict.get(key , myobject())
Note that this last one won't have the same result, since it won't store
my_obj under my_dict[key]. You'd have to use dict.setdefault :

my_obj = my_dict.setdefa ult(key, myobject())
I am wondering which one is the most recommended way?
It depends on the context. wrt/ 1 and 2, use 1 if you expect that most
of the time, my_dict[key] will not be set, and 2 if you expect that most
of the time, my_dict[key] will be set.
get usage seems
the clearest, but the only problem I see is that I think myobject() is
evaluated at call time,
Myobject will be instanciated each time, yes.
and so if the initialization is expensive you
will probably see surprises.
No "surprise" here, but it can indeed be suboptimal if instanciating
myobject is costly.
Jul 21 '07 #10

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

Similar topics

9
12240
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 them. What I want to do is filter out a subset of this dict to produce another dict that satisfies a set of criteria (in this case whether it contains all four values) to end up with something
6
3451
by: David Rasmussen | last post by:
If I have a collection of dicts like: john = {'id': 1, 'name': "John Cleese", 'year': 1939} graham = {'id': 2, 'name': "Graham Chapman", 'year': 1941} I could store all of them in a list. But for easy lookup, I might store all these in a dict instead, like people = {'1': john, '2': graham}
10
1536
by: Gregory Piñero | last post by:
Hey guys, I thought I'd throw this out there since everyone loves optimization questions (it's true, check out the number of replies to those type of questions!) Right now I have a function shown below. I want to combine two dictionaries and add the values together where-ever there is overlap. I figured this function would be reasonably fast, but I have around 1 million keys in each dictionary (~80% overlap) and it just runs all
3
3146
by: David MacKay | last post by:
Dear Greater Py, <motivation note="reading this bit is optional"> I am writing a command-line reader for python. I'm trying to write something with the same brevity as perl's one-liner eval "\$$1=\$2" while @ARGV && $ARGV=~ /^(\w+)=(.*)/ && shift;
3
2925
by: aking | last post by:
Dear Python people, im a newbie to python and here...so hello! Im trying to iterate through values in a dictionary so i can find the closest value and then extract the key for that value....what ive done so far: def pcloop(dictionary, exvalue): z = dictionary.itervalues() y = z - exvalue
16
2530
by: Andy Dingley | last post by:
I'm trying to write rot13, but to do it in a better and more Pythonic style than I'm currrently using. What would you reckon to the following pretty ugly thing? How would you improve it? In particular, I don't like the way a three-way selection is done by nesting two binary selections. Also I dislike stating the same algorithm twice, but can't see how to parameterise them neatly. Yes, I know of .encode() and .translate(). No, I...
3
5156
by: james_027 | last post by:
hi, a_dict = {'name':'apple', 'color':'red', 'texture':'smooth', 'shape':'sphere'} is there any difference between .. for key in a_dict: from
20
2427
by: Seongsu Lee | last post by:
Hi, I have a dictionary with million keys. Each value in the dictionary has a list with up to thousand integers. Follow is a simple example with 5 keys. dict = {1: , 2: , 900000: , 900001: ,
12
5011
by: Florian Brucker | last post by:
Hi everybody! Given a dictionary, I want to create a clustered version of it, collecting keys that have the same value: {1:, 2:, 3:} That is, generate a new dict which holds for each value of the old dict a list of the keys of the old dict that have that very value.
0
9568
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10164
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9835
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8833
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5277
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.