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?
You get a syntax error because the syntax for the python or operator is different, and you need to explicitly ask Python to return
Nonefrom a dictionary lookup using the.get()method:Because
.get()takes a default value to return instead of the looked-for key (which defaults toNone, you can also spell this as: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 returnmyhash['bar']and notmyhash['baz'].