Hello Python experts,
I am wondering if there is any shorter way to assign a value “A” to a variable if “A” is True (i.e. exists) and “B” if not.
Suppose I have:
mydict = {'a': 'apple', 'b': 'banana', 'c': 'Cherry'}
Then, as I understand, the shortest (well, one-line) way of assigning a value that does not exist as a key in this mydict var is:
myvar = mydict['m'] if 'm' in mydict else 'Melon'
But is there any shorter way of doing this?
In Ruby, I would go like this:
myvar = mydict[:m] || 'Melon'
Just wondering. Thanks in advance!
In this particular case (getting an item from a dictionary), there’s a shortcut available – the
getmethod, which allows a default value.