Initialize Python variable from possible missing dict value?

(Note that this is not exactly equivalent to your code, since it will use 1024 only if the key index is not present, while your code also uses 1024 when the value corresponding to key index is falsy. From your explanation I infer the former is what you actually want. ).

Value = mydict. Get('index', 1024) (Note that this is not exactly equivalent to your code, since it will use 1024 only if the key index is not present, while your code also uses 1024 when the value corresponding to key index is falsy. From your explanation I infer the former is what you actually want.).

1 It is critically important to note that, because python is a non-lazy language, the "default value" expression will be evaluated whether or not you actually end up using it. (In contrast to an if statement which will not evaluate it. ) – ninjagecko May 30 '11 at 23:45 @ninjagecko is right - if the default value is expensive to construct and you care about performance you'll want to avoid using get/setdefault.

I often use a try: ... except KeyError: idiom in this case, especially if I expect the key 'misses' to be rare. – Whatang May 31 '11 at 0:11 @ninjagecko, Whatang: value = mydict'index' if 'index' in mydict else 1234 is the lazy oneliner. I just want to make it clear that it does not matters here, because 1234 is extremely cheap to create.

– Jochen Ritzel May 31 '11 at 1:16 if the default value is expensive and the value from the dict will be non-falsey then you can do value = mydict. Get('index') or doexpensiveoperation() which is not as nice but still pretty short. – lambacck May 31 '11 at 2:57 @lambacck: This will give an unexpected result if index is in the dictionary, but its assigned value is falsy.

– Sven Marnach May 31 '11 at 10:45.

Alternatively use setdefault() - like get(), but it inserts the key before returning the value: value = mydict. Setdefault('index', 1024).

It is critically important to note that, because python is a non-lazy language, the "default value" expression will be evaluated whether or not you actually end up using it. (In contrast to an if statement which will not evaluate it. ) – ninjagecko May 30 '11 at 23:45.

The get and setdefault methods are important to know, they should be in any Python programmer's toolbox. Another important way of doing this is to use collections. Defaultdict, because then you can define your "default" in a single place without having to scatter it throughout your code wherever the dictionary is used, i.e.

Don't Repeat Yourself. Then if you change the default you don't need to hunt through your code finding all those gets and setdefaults. For example >>> import collections >>> myDict = collections.

Defaultdict >>> myDict = collections. Defaultdict(lambda : 1024) >>> myDict0 += 1 >>> print myDict0, myDict100 1025 1024 Because you get to set the function call, you can do whatever you like for your default value. How about assigning a random value between 1 and 10 for every new key?

>>> import collections >>> import random >>> myDict = collections. Defaultdict(lambda : random. Randint(1,10)) >>> print myDict0, myDict100 1 5 >>> print myDict0, myDict100, myDict2 1 5 6 OK, that example's a little contrived, but I'm sure you can think of better uses.

Say you have an expensive class to construct - the instance is only created if the key is not actually present, unlike when calling get and setdefault, e.g. >>> class ExpensiveClass(object): >>> numObjects = 0 >>> def __init__(self): >>> ExpensiveClass. NumObjects += 1 >>> >>> print ExpensiveClass. NumObjects 0 >>> x = {} >>> x0 = ExpensiveClass() >>> print ExpensiveClass.

NumObjects 1 >>> print x. Get(0, ExpensiveClass()) >>> print ExpensiveClass. NumObjects 2 >>> ExpensiveClass.

NumObjects = 0 >>> z = collections. Defaultdict(ExpensiveClass) >>> print ExpensiveClass. NumObjects 0 >>> print z0 >>> >>> print ExpensiveClass.

NumObjects 1 Note that the call to x. Get constructs a new ExpensiveClass instance, even though we don't ever use that instance because x0 already exists. This could cause problems if you were indeed trying to count the number of ExpensiveClass objects, or if they were very slow to create.

These problems don't occur for collections.defaultdict" rel="nofollow">collections.defaultdict" rel="nofollow">collections.defaultdict" rel="nofollow">collections.defaultdict.

It's also worth noting that setdefault() and defaultdict both have the side-effect of adding any missing key to the dictionary. Also when using a defaultdict you may need more than a simple default_factory function if you want the default value to vary depending on the key (because the factory function is not passed the key being look-up). – martineau May 31 '11 at 0:57 1 One other things, defaultdict wasn't added until Python 2.5 (and the OP is using 2.4).

– martineau May 31 '11 at 1:11 defaultdict seems amazing because it is lazy, so the lambda isn't evaluated unless it's needed; wish I could upvote more – ninjagecko May 31 '11 at 1:46 @martineua oops, sorry missed the Python 2.4. And yes, absolutely, sometimes defaultdict can be a little limiting because you can't specify the key to the factory function. – Whatang May 31 '11 at 1:46.

The collections module defaultdict class might be of help. Unfortunately it wasn't introduced until Python 2.5 and it doesn't do exactly what your code does. Here's a few differences: It only supplies a value when a key is missing, not when it is there but has a value considered False.

If the looked-up key is missing it will add it to the dictionary with a default value as well as return the default value. All missing values get the same default value. If that's OK you can emulate the essence of one in older Pythons with something like this: try: from collections import defaultdict except ImportError: class defaultdict(dict): def __init__(self, default_factory=None, *a, **kw): dict.

__init__(self, *a, **kw) self. Default_factory = default_factory def __getitem__(self, key): try: return dict. __getitem__(self, key) except KeyError: return self.

__missing__(key) def __missing__(self, key): selfkey = value = self. Default_factory() return value A recipe for a more complete emulation is available on ActiveState. Even if you had Python 2.5+, you might want to derive your own class to customize to have the exact behavior you wanted.

Besides checking for "False" truth values and perhaps not adding any missing ones to the dictionary, you could also provide it with a separate dictionary of multiple default values corresponding to different keys instead of "one size fits all". For ways to do that see Is there a way to set multiple defaults on a Python dict using another dict?.

1 for the basic fallback implementation. – lambacck May 31 '11 at 2:59.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions