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 if
s in a row.
没有评论:
发表评论