Python字典值检查不为空而不是None

Ana*_*and 4 python python-2.7

我有一本字典,可能有也可能没有一个或两个键'foo'和'bar'.根据两者是否可用,我需要做不同的事情.这是我正在做的(它的工作原理):

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()
Run Code Online (Sandbox Code Playgroud)

这似乎太冗长了 - 在Python(2.7.10)中这样做的惯用方法是什么?

Chr*_*ean 5

您可以dict.get()用来缩短代码.而不是提出KeyError时,键不存在,None则返回:

foo = data.get('foo')
bar = data.get('email')

if foo is not None and bar is not None:
    dofoobar()
elif foo is not None:
    dofoo()
elif bar is not None:
    dobar()
Run Code Online (Sandbox Code Playgroud)