print(type(test['airport']['origin']))是一个班级无类型和类字典
如果那是总是所以,那个错误永远不会在test['airport']['origin']['position']. (这两行是您的 sn-p 中此错误的唯一可能来源。)
如果没有你使用的list_of_details_per_flight,我无法测试其中的任何一个,但我可以建议 3 种可能的方法来解决这个问题而不会引发错误:
建议一:增加条件
您可以单独检查是否可以访问 3 个键中的每一个。
for test in list_of_details_per_flight:
for k in ['airport', 'origin', 'position']:
if not isinstance(test, dict):
# print(f"can't access ['{k}'] of {type(test)} {test}")
break
if k not in test:
# print(f"no value for ['{k}'] in {test}")
break
test = test[k] ## OR JUST
# test = test.get(k) ## [ if you want to omit the if k not in test block ]
建议 2:只需从 try 块内打印
for test in list_of_details_per_flight:
try: print(test['airport']['origin']['position'])
except: pass ## OR
# except Exception as e: print(type(e), e) # print an error msg for that test
建议3:打印所有position值
我有一个 set of functions 可用于检索全部list_of_destinations 中的值与 position 作为键配对。
allPos = getNestedVal(
list_of_destinations, nKey='position', rForm='_all',
pKeys=[], objName='list_of_destinations'
)
for pos in allPos: print(pos['val'], '<---', pos['expr'])
- 如果您只想要
airport 内的origin 内的position 值,请通过pKeys=['airport', 'origin']到getNestedVal(指定父键)。
-
pos['expr'] 将包含完整的密钥路径,例如list_of_destinations[0]['airport']['origin']['position']等等,但是如果你只想要所有的值,你可以通过设置将它们放在一个平面列表中rForm='just_vals_all'.
您还可以通过在 except 块中打印 test 中的所有 position 值来组合最后两个建议。
for test in list_of_details_per_flight:
try: print(test['airport']['origin']['position'])
except Exception as e: : pass ## OR
# print(type(e), e) # print an error msg for that test
tPos = getNestedVal(test, nKey='position', rForm='_all', pKeys=[], objName='test')
# if not tPos: print(' This test contains no position values')
for pos in tPos: print(' ', pos['val'], '<---', pos['expr'])
- 如果您只需要第一个
position 值而不是所有值的列表,请删除_all来自rForm 的结尾。
笔记:getNestedVal 如果list_of_details_per_flight很大;它主要用于一次性查找深层嵌套字典中某些值的路径中的键列表,然后从那时起使用这些路径。