Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A d.get inside a d.get:

Maybe try a double dict.get:

val = d.get("k1", d.get("k2", None))

And now:

print(val)

Would give k1's value if there is a k1 and k2's value if there isn't a key named k1, but if there also isn't a k2, it gives None.

My code does a d.get, but inside the parameters the second argument you did None, in this case we do another d.get, which is for k2, and in the second d.get it finally has the second argument as None, it only gives None if both of the keys are not in d.

Edit:

If there are more keys (i.e. k3, k4 ...), just add more d.gets:

val = d.get("k1", d.get("k2", d.get("k3", d.get("k4"))))

And just add a:

print(val)

To output it.

Using a generator with next:

You could also use a generator with next to get the first value, like this:

val = next((d[i] for i in ['k1', 'k2', 'k3', 'k4'...] if i in d), None)

And now:

print(val)

Would also give the right result.

Remember to add a None so that if there aren't any values from any of those keys it won't give a StopIteration.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...