Col*_*len 6 python python-2.7 data-structures
我有一个嵌套OrderedDict,我想从中提取一个值.但在我提取该值之前,我必须确保存在一长串属性,并且它们的值不是无.
改进以下代码的最pythonic方法是什么:
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']
Run Code Online (Sandbox Code Playgroud)
另一种get()方法是使用该方法:
x = data.get('first', {}).get('second', {}).get('third', None)
Run Code Online (Sandbox Code Playgroud)
如果在任何时候钥匙不存在,那么 x = None