Pythonic way of setting a default
Is there a simple way of of sett开发者_运维问答ing 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
Doesn't anyone read the documentation?
foo.setdefault('bar', 123)
You could check out defaultdict
(Wrong first part of the answer edited away)
Dict
s have a setdefault()
method that works just as get()
, only it inserts the value if the key was missing.
foo.setdefault('bar', 123)
Cheers.
精彩评论