Python Dictionary Values ​​Validated Not Null, Not None

I have a dictionary that may or may not have one or both of the keys "foo" and "bar". Depending on whether both or both 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
source share
4 answers

Here is 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 am not sure if this is cleaner or more readable than ChristianDean's answer.

Just for fun, you can also use dictwith boolean tuples as keys and functions as values:

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

You would use it like this:

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!
+3
source

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

try/except.Also get

-1

Source: https://habr.com/ru/post/1685972/


All Articles