Jack022
Jack022

Reputation: 1257

Keyerror when using Json in python

I'm using a basic script to retrieve some trading data from an exchange, here is the response:

{'info': {'symbol': 'ETHBTC',
  'orderListId': -1,
  'price': '0.01083700',
  'origQty': '0.01800000',
  'executedQty': '0.00000000',
  'cummulativeQuoteQty': '0.00000000',
  'status': 'NEW',
  'timeInForce': 'GTC',
  'type': 'LIMIT',
  'side': 'BUY',
  'stopPrice': '0.00000000',
  'icebergQty': '0.00000000',
  'time': 1567078061338,
  'updateTime': 1567078061338,
  'isWorking': True}}

Now i want to print some parts of this response individually.

If i try:

tot = exchange.fetch_open_orders()
    for x in tot:
        print(x['symbol'])

I'll get: 'ETHBTC'. Until now, everything is normal.

But if i try:

tot = exchange.fetch_open_orders()
    for x in tot:
        print(x['origQty']) 

I get a KeyError: 'origQty', which is weird, because this error should appear when i try to reference a parameter which doesn't exist, but it exists, since it is in my response. What am i doing wrong?

Upvotes: 0

Views: 134

Answers (2)

Akash Pagar
Akash Pagar

Reputation: 637

Here you iterating dictionary on keys, so each time you are trying to get value from key, that's why it is giving KeyError. This occurs when a key which is not present in a dictionary and still it accessed. This can be achieved by following way.

for x in tot:
    print(tot[x].get('symbol'))
    print(tot[x].get('origQty'))

Give output

ETHBTC
0.01800000

Upvotes: 1

Akash Kumar
Akash Kumar

Reputation: 1406

I am not sure what is the format of tot. But you can try this.

for x, v in dict(tot).items():
    print(v['symbol'])
    print(v['origQty'])

Output:

ETHBTC
0.01800000

Upvotes: 0

Related Questions