Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dict easiest and cleanest way to get value of key2 if key1 is not present

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.

like image 403
Sreeram TP Avatar asked Dec 05 '22 08:12

Sreeram TP


1 Answers

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'
like image 57
PacketLoss Avatar answered Dec 08 '22 00:12

PacketLoss