if 'value1' in results_dict:
if results_dict['value1'] is not None:
if results_dict['value1']['limit'] is None:
res.append(results_dict['value1']['limit'] == "Nan")
else:
res.append(results_dict['value1']['limit'])
else:
res.append(results_dict['value1']['limit'] == "Nan")
else:
res.append("Nan")
我正在尝试解决不允许我将值附加到“res”的问题 (res.append(results_dict['value1']['limit'] == "Nan"))
I am getting TypeError: 'NoneType' object is not subscriptable
I am trying to check if there is a None value and replacing it with NaN. I also want to keep the key
names. I also used .get twice but that gave me an Attribute Error.
最佳答案
您的代码的常规 Pythonic 习惯用法有点不对劲,您不想使用“is None”( list of things Python returns as None ),而且,对于 nan 测试,您需要导入数学。我相信这就是您正在寻找的:
import math
if 'value1' in results_dict:
if results_dict['value1']: #is not None just means it exists, so eliminate that
if not results_dict['value1']['limit']: #is None just means not
temp = {'limit':math.nan} #create new dict
results_dict['value1'].update(temp) #update your level 1 nested dict
res.append(math.isnan(results_dict['value1']['limit'])) #correct nan test
else:
res.append(results_dict['value1']['limit'])
else:
res.append(math.isnan(results_dict['value1']['limit'])) #correct test for nan
else:
res.append(math.nan) #correct assignment of nan
另请参阅: Assigning a variable NAN in Python
编辑:如果您不希望专门分配 NAN,那么您的代码可以大大简化。
if 'value1' in results_dict:
if results_dict['value1']:
if results_dict['value1']['limit']:
res.append(results_dict['value1']['limit'])
else:
res.append('')
else:
res.append('') #correct assignment of nan
实际上,真的不清楚这里的问题是什么......您的资源应该是一个列表?真理值(value)观?字典值?
关于Python 嵌套字典替换为 none 并追加而不使用 get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58070463/