<p>我有一本字典,可能有也可能没有一个或两个键“foo”和“bar”。根据两者是否都有,我需要做不同的事情。以下是我正在做的事情(而且很管用):</p>
<pre><code>foo = None
bar = None
if 'foo' in data:
if data['foo']:
foo = data['foo']
if 'bar' in data:
if data['bar']:
bar = data['bar']
if foo is not None and bar is not None:
dofoobar()
elif foo is not None:
dofoo()
elif bar is not None:
dobar()
</code></pre>
<p>这似乎太冗长了——在Python(2.7.10)中,使用什么惯用方法来实现这一点?在</p>
<pre><code>>>> data = {'foo': 1}
>>> foo = data.get('foo')
>>> foo
1
>>> bar = data.get('bar')
>>> bar
>>> bar is None
True
</code></pre>