Python字典值检查not empty和not Non

2024-09-25 04:31:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典,可能有也可能没有一个或两个键“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()

这似乎太冗长了——在Python(2.7.10)中,使用什么惯用方法来实现这一点?在


Tags: andinnonedataif字典foois
3条回答
>>> data = {'foo': 1}
>>> foo = data.get('foo')
>>> foo
1
>>> bar = data.get('bar')
>>> bar
>>> bar is None
True

您可以使用^{}来缩短代码。不是在键不存在时引发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()

以下是重构代码的另一种方法:

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

if foo:
    if bar:
        dofoobar()
    else:
        dofoo()
elif bar:
    dobar()

不过,我不确定这是否比克里斯蒂安的回答更清晰或更易读。在

为了好玩,您还可以使用dict,布尔元组作为键,函数作为值:

^{pr2}$

你应该这样使用它:

data = {'foo': 'something'}

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

def dofoobar():
    print('foobar!')

def dobar():
    print('bar!')

def dofoo():
    print('foo!')

actions = {(True, True):dofoobar, (False, True):dobar, (True, False):dofoo}
action = actions.get((foo is not None, bar is not None))
if action:
    action()
#foo!

相关问题 更多 >