检查字典键是否存在并具有值的有效方法
我们假设有一本字典如下:
Let's say there's a dictionary that looks like this:
d = {"key1": "value1", "key2": {"key3": "value3"}}
字典可能包含或可能不包含 key2
,而且 key2
可能为空.因此,为了获得 value3
,我需要检查 key2
及其值是否存在非空值, key3
也是如此.
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']
现在,我想知道是否有一个更简单的解决方案,所以我不必连续写3个 if
.
Now, I wonder if there's a simpler solution so I don't have to write 3 if
s in a row.
一种方法是预见故障并予以捕获:
One approach would be to expect the failure and catch it:
try:
value = d['key2']['key3']
except (KeyError, TypeError):
pass
(不要将变量命名为类型的名称,这是一种不好的做法,我已将其重命名为 d
)
(don't call your variable the name of the type, it's a bad practice, I've renamed it d
)
KeyError
捕获丢失的键, TypeError
捕获尝试索引不是 dict
的内容的
The KeyError
catches a missing key, the TypeError
catches trying to index something that's not a dict
.
如果您希望这种失败非常普遍,那么这可能并不理想,因为 try ..除了
块有一些开销.
If you expect this failure to be very common, this may not be ideal, as there's a bit of overhead for a try .. except
block.
在这种情况下,尽管我将其写为:
In that case you're stuck with what you have, although I'd write it as:
if 'key2' in d and d['key2'] and 'key3' in d['key2']:
value = d['key2']['key3']
或者可能更清楚一点:
if 'key2' in d and isinstance(d['key2'], dict) and 'key3' in d['key2']:
value = d['key2']['key3']
如果您要在 else
部分的 value
中分配其他内容(例如 None
),则还可以考虑:
If you're about to assign something else to value
in the else
part (like None
), you could also consider:
value = d['key2']['key3'] if 'key2' in d and d['key2'] and 'key3' in d['key2'] else None