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.get
s:
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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…