-2
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?

Dijkgraaf
  • 11,049
  • 17
  • 42
  • 54
user11629
  • 109
  • 5
  • It doesn’t go into the else, because the condition is raising an error. You need to check if the key exists in a way that *doesn't* raise an error, but just produces a True/False. – deceze Aug 24 '23 at 01:24
  • 2
    `# if symbol exists in json file` that is not what that code does. That code tries to *retrieve* `symbol` from the `ts_dict`. If that key doesn't exist, it raises a `KeyError`. An unhandled exception will terminate the program – juanpa.arrivillaga Aug 24 '23 at 01:25

2 Answers2

1

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}]
Jiu_Zou
  • 463
  • 1
  • 4
0

You could use dict.setdefault

ts_dict.setdefault(symbol, []).append({'datetime': dt_string, 'ts_after': ts})
Jab
  • 26,853
  • 21
  • 75
  • 114