Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have a defined or operator like Perl? [duplicate]

Tags:

python

In Perl I can do something like this:

foo = a // b;

What I'm wondering is if Python has anything similar to this. I've tried the following, but obviously it does not work:

foo = {'key1':'val1','key2':'val2'}
bar = foo['doesntexist'] or foo['key1']

And I get the error:

KeyError: 'doesntexist'
like image 700
Franz Kafka Avatar asked Aug 31 '25 05:08

Franz Kafka


2 Answers

You don't need the or at all:

bar = foo.get('doesntexist', foo['key1'])
like image 72
Francisco Avatar answered Sep 02 '25 19:09

Francisco


The reason your method is not working is because Python raises an error before your boolean expression is able to be evaluated. Instead of simply indexing the dictionary, you need to use .get() instead. Rather than raising an error, .get() returns None which allows your expression to be evaluated correctly:

bar = foo.get('doesntexist') or foo.get('key1')

Note that if the value of the first key is 0 or any other value that evaluates to false, your method will fail. If this is fine with you than use the method above.

However, if you'd like not to have the behavior described above, you must test if the first value is None. At this point however, it would be better to simply extract this logic to a separate function:

def get_key(d, test_key, default_key):
    """
    Given a dictionary(d), return the value of test_key.
    If test_key does not exists, return the default_key 
    instead.
    """
    if d.get(test_key) is not None:
        return d.get(test_key)
    return d.get(default_key)

Which can be used like so:

foo = {'key1':'val1','key2':'val2'}
bar = get_key(foo, 'doesntexist', 'key1')
like image 44
Christian Dean Avatar answered Sep 02 '25 18:09

Christian Dean