检查父字典是否不为空,并获取嵌套字典的值 [英] Check if parent dict is not empty and retrieve the value of the nested dict
问题描述
让我们假设我有一个嵌套的字典,看起来像这样:
Let's suppose that I have a nested dictionary which looks like that:
parent_dict = { 'parent_key': {'child_key': 'child_value'}
如何编写以下代码:
if parent_dict.get('parent_key') is not None and parent_dict['parent_key']['child_key']=='value_1':
print('Value detected')
在可读性和代码数量方面以更有效的方式?
in a more efficient way in terms of readability and amount of code?
具体来说,我认为第一个if条件可以与第二个条件以某种方式整合在一起.
Specifically I think that the first if condition could be somehow integrated with the second one in one condition.
因此,我希望这样:
if condition_x:
print('Value detected')
其中, condition_x
会检查 parent dict
是否不为空,如果不是,则返回 child dict
的值,否则返回无
.
where condition_x
checks both if the parent dict
is not empty and if not then it returns the value of the child dict
otherwise it returns None
.
推荐答案
,您可以使用 dict.get
方法:
you could use the dict.get
method:
if parent_dict.get('parent_key', {}).get('child_key') == 'value_1':
...
如果存在,
dict.get(key)
将返回 dict [key]
;否则,返回 dict [key]
.否则将返回 None
.如果密钥不存在,则 dict.get(key,default)
将返回 default
.将默认值设置为空dict {}
将使第二个 .get
工作.
dict.get(key)
will return dict[key]
if the key exists; otherwise it will return None
.dict.get(key, default)
will return default
if the key does not exist. setting the default value to an empty dict {}
will make the second .get
work.
这篇关于检查父字典是否不为空,并获取嵌套字典的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!