I have a python dict like this,
d = {
"k1" : "v1",
"k2" : "v2"
}
I want to pick up value of k1 from dict, which I can do like this,
d.get("k1")
But the problem is, sometimes k1 will be absent in the dict. In that case, I want to pick k2 from the dict. I do it like this now
val = d.get("k1", None)
if not val:
val = d.get("k2", None)
I can do like this as well,
if "k1" in d:
val = d['k1']
else:
val = d.get("k2", None)
These solutions look okay and works as expected, I was wondering if there exists a one-liner solution to this problem.
The None
in d.get()
specifies what to do if nothing is found.
Simply add another d.get()
instead of None
.
d.get('k1', d.get('k2', None))
#'v1'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With