1
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")

I am trying to fix an issue that is not allowing me to append values to '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.
4212extra
  • 81
  • 1
  • 7

1 Answers1

1

The coventional Pythonic idiom for your code is a bit off, you don't want to use 'is None', (list of things Python returns as None), and also, for nan testing you need to import math. I believe this is what you are looking for:

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

See also: Assigning a variable NAN in Python

Edit: if you are not looking to assing NAN specifically, then your code can be greatly simplified.

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

Actually it's really not clear what the question is here... What is your res supposed to be a list of? Truth values? Dict values?

neutrino_logic
  • 1,289
  • 1
  • 6
  • 11
  • Thanks! I am not looking to add Nan. It can be anything like empty. – 4212extra Sep 23 '19 at 22:16
  • In that case, just use an empty string, two single quotes, in place of math.nan. Although that was what you were testing for, wasn't it? So you can eliminate most of that inner if statement, just make the inner 'else:' into 'if results_dict['value1']['limit']:' and then all the other res.append(...) into res.append('') (or res.append(0) if that makes more sense in your code, i.e. is res a list of strings or a list of numbers?) – neutrino_logic Sep 23 '19 at 22:34
  • res is just that needs to have all of these dictionaries values. The dictionary values come from a JSON config file. The final goal is to create a data frame. – 4212extra Sep 23 '19 at 22:58