Is there a simple way of of setting a default in python - specifically setting a default in a dict?
For instance, let's say I have a dict called foo, which may or may not have something assigned on the key bar. The verbose way of doing this is:
if not foo.has_key('bar'):
foo['bar'] = 123
One alternative would be:
foo['bar'] = foo.get('bar',123)
Is there some standard python way of doing this - something like the following, but that actually works?
foo['bar'] ||= 123
3 Answers 3
Doesn't anyone read the documentation?
foo.setdefault('bar', 123)
Comments
You could check out defaultdict
1 Comment
request.session in Django, so I can't redefine it to be a defaultdict.(Wrong first part of the answer edited away)
Dicts have a setdefault() method that works just as get(), only it inserts the value if the key was missing.
foo.setdefault('bar', 123)
Cheers.
1 Comment
foo.get('bar') or 123 is quite different than checking foo.has_key('bar'). Consider foo['bar'] = 0.
has_key()use'bar' in footo test for membership.has_key()is deprecated docs.python.org/library/stdtypes.html#dict.has_key (it is removed since python3.0). The reason might be "There should be one-- and preferably only one --obvious way to do it."