在python中使用Json时出现Keyerror

2024-10-02 14:19:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用一个基本脚本从交易所检索一些交易数据,下面是响应:

{'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}}

现在我想单独打印这个回复的一些部分。你知道吗

如果我尝试:

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

我会得到:'ETHBTC'。直到现在,一切都很正常。你知道吗

但如果我尝试:

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

我得到了一个KeyError: 'origQty',这很奇怪,因为当我尝试引用一个不存在但存在的参数时,应该会出现这个错误,因为它在我的响应中。我做错什么了?你知道吗


Tags: 数据ininfo脚本forexchange交易fetch
2条回答

我不确定tot的格式是什么。但你可以试试这个。你知道吗

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

输出:

ETHBTC
0.01800000

这里是对键的迭代字典,所以每次尝试从键获取值时,它都会给出KeyError。 当一个键在字典中不存在但仍被访问时,就会发生这种情况。 这可以通过以下方式实现。你知道吗

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

输出

ETHBTC
0.01800000

相关问题 更多 >