Python dictionary values check not empty and not None

Viewed 2944

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

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

Here's another way to refactor your code :

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

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

I'm not sure it's cleaner or more readable than ChristianDean's answer, though.

Just for fun, you could also use a dict with boolean tuples as keys and functions as values:

{(True, True):dofoobar, (False, True):dobar, (True, False):dofoo}

You'd use it this way:

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!
>>> data = {'foo': 1}
>>> foo = data.get('foo')
>>> foo
1
>>> bar = data.get('bar')
>>> bar
>>> bar is None
True
foo = None
bar = None

try:
  foo=data["foo"]
except:
  pass

try:
  bar=data["bar"]
except:
  pass



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

You can use try/except.Also get attribute is also perfect

Related