pythonconditional-statementstry-exceptcontextmanager

Python conditional fails to reach the else statement when the if statement is not satisfied


try:
            symbol = input("Specify symbol: ").upper()
            dt_string = input("Specify datetime in isoformat (e.g.'2021-05-27T03:30:00+00:00'): ")
            try:
                dt = datetime.fromisoformat(dt_string)
            except Exception as e:
                print(e)
            ts = Decimal(input("Specify ticksize after: "))
        except Exception as e:
            print(e)
        else:
            with open(join(file_directory, "ticksize_changes.json"), "r") as f:
                ts_dict = json.load(f)
                print(ts_dict)
                if ts_dict[symbol]: # if symbol exists in json file
                    ts_dict[symbol].append({'datetime': dt_string, 'ts_after': ts})
                else:
                    ts_dict[symbol] = [{'datetime': dt_string, 'ts_after': ts}]
            with open(join(file_directory, "ticksize_changes.json"), "w") as f:
                json.dump(ts_dict, f, default=str)

I have a try-except-else structure, and in the else, I have a with statement. In that with statement, I have a simple if-else. I tried a case where the if statement executed successfully, but as soon as I tried a case where it should reach the else statement I get the following error: Error

The console message is correct - indeed no such key exists. But why does the else statement fail to execute?


Solution

  • you should use this statement, first make sure the dictionary keys containing it.

    if symbol in ts_dict.keys(): # if symbol exists in json file
        ts_dict[symbol].append({'datetime': dt_string, 'ts_after': ts})
    else:
        ts_dict[symbol] = [{'datetime': dt_string, 'ts_after': ts}]