0

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
4
  • don't use has_key() use 'bar' in foo to test for membership. Commented Feb 19, 2011 at 16:55
  • @J.F. Sebastian Why? has_key seems more explicit to me - is there some case where 'bar' in foo is more appropriate? Besides when foo isn't necessarily a dict? Commented Feb 20, 2011 at 21:38
  • 1
    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." Commented Feb 20, 2011 at 21:49
  • @J. F. Sebastian - good to know - thanks. Commented Feb 20, 2011 at 22:03

3 Answers 3

5

Doesn't anyone read the documentation?

foo.setdefault('bar', 123)
Sign up to request clarification or add additional context in comments.

Comments

3

You could check out defaultdict

1 Comment

+1 Since that looks interesting for future purpose. Unfortunately, right now, I'm dealing with request.session in Django, so I can't redefine it to be a defaultdict.
1

(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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.