Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary values check not empty and not None

I have a dictionary which may or may not have one or both keys 'foo' and 'bar'. Depending on whether both or either are available, I need to do different things. Here is what I am doing (and it works):

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

This seems too verbose - what is the idiomatic way to do this in Python (2.7.10)?

like image 586
Anand Avatar asked Jan 04 '23 10:01

Anand


1 Answers

You can use dict.get() to shorten your code. Rather than raising a KeyError when a key is not present, None is returned:

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()
like image 70
Christian Dean Avatar answered Jan 14 '23 19:01

Christian Dean