tags:

views:

136

answers:

2

What's the most succinct way of saying, in Python, "Give me dict['foo'] if it exists, and if not, give me this other value bar"? If I were using an object rather than a dictionary, I'd use getattr:

getattr(obj, 'foo', bar)

but this raises a key error if I try using a dictionary instead (a distinction I find unfortunate coming from JavaScript/CoffeeScript). Likewise, in JavaScript/CoffeeScript I'd just write

dict['foo'] || bar

but, again, this yields a KeyError. What to do? Something succinct, please!

+7  A: 

dict.get(key, default) returns dict[key] if key in dict, else returns default.

Note that the default for default is None so if you say dict.get(key) and key is not in dict then this will just return None rather than raising a KeyError as happens when you use the [] key access notation.

mikej
Thanks, that's just what I was looking for! I think you just set a new speed record.
Trevor Burnham
A: 

Also take a look at collections module's defaultdict class. It's a dict for which you can specify what it must return when the key is not found. With it you can do things like:

class MyDefaultObj:
    def __init__(self):
        self.a = 1

from collections import defaultdict
d = defaultdict(MyDefaultObj)
i = d['NonExistentKey']
type(i)
<instance of class MyDefalutObj>

which allows you to use the familiar d[i] convention. However, as mikej said, this also works:

d = {}
i = d.get('NonExistentKey') | MyDefaultObj()
ddotsenko