2021年4月5日星期一

Efficient way to check if dictionary key exists and has value

Let's say there's a dictionary that looks like this:

d = {"key1": "value1", "key2": {"key3": "value3"}}  

The dictionary may or may not contain key2, also key2 might be empty. So in order To get value3, I would need to check if key2 and its value exist with non-null values, same applies for key3.

Now the obvious stupid solution would be like this:

if 'key2' in d:      if d['key2']:          if 'key3' in d['key2']:              value = d['key2']['key3']  

Now, I wonder if there's a simpler solution so I don't have to write 3 ifs in a row.

https://stackoverflow.com/questions/66937258/efficient-way-to-check-if-dictionary-key-exists-and-has-value April 04, 2021 at 09:22AM

没有评论:

发表评论