Python 检查嵌套属性是否存在
我有一个嵌套的Python 检查嵌套属性是否存在,python,python-2.7,data-structures,Python,Python 2.7,Data Structures,我有一个嵌套的OrderedDict,我想从中提取一个值。但在提取该值之前,我必须确保存在一长串属性,并且它们的值不是零 改进以下代码的最具python风格的方法是什么: if 'first' in data and \ data['first'] and \ 'second' in data['first'] and \ data['first']['second'] and \ 'third' in data['first']['second'] and \
OrderedDict
,我想从中提取一个值。但在提取该值之前,我必须确保存在一长串属性,并且它们的值不是零
改进以下代码的最具python风格的方法是什么:
if 'first' in data and \
data['first'] and \
'second' in data['first'] and \
data['first']['second'] and \
'third' in data['first']['second'] and \
data['first']['second']['third']:
x = data['first']['second']['third']
另一种方法是使用
get()
方法:
x = data.get('first', {}).get('second', {}).get('third', None)
如果钥匙在任何一点不存在,则
x=None
您可以将其环绕在try/except块中,如下所示:
try:
x = data['first']['second']['third']
assert x
except KeyError, AssertionError:
pass
assert
不应在此处使用。他希望确保该值不是None,这就是它存在的原因。我是否需要为每个附加的赋值使用另一个try-catch块?例如,x=data['a']
和y=data['b']
。仅当您不确定“a”和“b”是数据中的键时。如果其中一个字段设置为“无”,则此操作无效。e、 g.data={'first':{'second':None}