Reputation: 2019
In Ruby, if you want to set the value of a variable conditionally, you can do something like this:
foo = myhash[ "bar" ] || myhash[ "baz" ]
And it will set the value of foo to myhash[ "bar" ] if it exists, otherwise it will set foo to myhash[ "baz" ]. If neither exist, it will set foo to nil.
In Python, you will get a syntax error if you try this type of assignment. Moreover, Python will throw a KeyError on myhash[ "baz" ] instead of setting it to None. It seems to me that the only way to conditionally set foo in Python is to write a big multi-line conditional statement, but I would really love to just do this in one line like Ruby. Is there any way to do this?
Upvotes: 2
Views: 239
Reputation:
foo = myhash.get('bar', myhash['baz'])
This does raise an error if the 'baz' key is not present, but I'd consider that a bug anyway and wouldn't want the language to silent it. If the second item is also optional and you want None
as final fallback, you can also use .get
for the second lookup.
Upvotes: 0
Reputation: 1122502
You get a syntax error because the syntax for the python or operator is different, and you need to explicitly ask Python to return None
from a dictionary lookup using the .get()
method:
foo = myhash.get('bar') or myhash.get('baz')
Because .get()
takes a default value to return instead of the looked-for key (which defaults to None
, you can also spell this as:
foo = myhash.get('bar', myhash.get('baz'))
This has the added benefit that if myhash['bar']
is false-y (evaluates to False in a boolean context, such as empty sequences or numerical 0) it'll still return myhash['bar']
and not myhash['baz']
.
Upvotes: 4