Python 嵌套字典替换为 none 并追加而不使用 get

标签 python python-3.x pandas dictionary

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/

相关文章:

python - 在 python 3.x 中有效地搜索多个文件的关键字的最佳方法?

python - sys.getrefcount返回不同范围的非连续值

python - 标记数据时出错。 C 错误 : out of memory pandas python, 大文件 csv

python - Azure 上带有 Windows Docker 容器的 Django Web 应用程序 : Invalid HTTP_HOST header: '10.40.0.7:30015' . 您可能需要将 '10.40.0.7' 添加到 ALLOWED_HOSTS

java - 规范驱动的数据包格式解析?

Python UTF-8 比较

python - 从 python 字典中删除\n

python - 通过在Python中添加全局变量名称和字符串来创建df列名称

python - 为什么在 Folium 中使用超过 100 个圆形标记进行绘图会导致 map 空白?

Python tkinter 标签方向