本文介绍了Python:调用Dict中的有效键/索引时出现KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些要从websocket中提取的JSON数据:

I have some JSON data that I'm pulling from a websocket:

while True:
    result = ws.recv()
    result = json.loads(result)

这里是打印(结果):

{'type': 'ticker', 'sequence': 4779671311, 'product_id': 'BTC-USD', 'price': '15988.29000000', 'open_24h': '14566.71000000', 'volume_24h': '18276.75612545', 'low_24h': '15988.29000000', 'high_24h': '16102.00000000', 'volume_30d': '1018642.48337033', 'best_bid': '15988.28', 'best_ask': '15988.29', 'side': 'buy', 'time': '2018-01-05T15:38:21.568000Z', 'trade_id': 32155934, 'last_size': '0.02420000'}

现在,我要访问价格" 值.

print (result['price'])

此结果出现KeyError:

This results with a KeyError:

File "C:/Users/Selzier/Documents/Python/temp.py", line 43, in <module>
    print (result['price'])
KeyError: 'price'

但是,如果我对(结果)数据执行循环,那么我可以成功打印 i result [i]

However, if I perform a loop on the (results) data, then I can successfully print both i and result[i]

  for i in result:
        if i == "price":
            print (i)
            print (result[i])

将打印以下数据:

price
16091.00000000

为什么在致电时会收到"KeyError"消息?

Why do I get a 'KeyError' when calling:

result['price']

AND

result[0]

当我不在因我而生" 循环中时吗?

推荐答案

while True循环中创建防护,例如在for循环中:

Create a guard in while True loop, like in for loop:

while True:
    result = ws.recv()
    result = json.loads(result)
    if result and 'price' in result:
        print(result['price'])
    ...

(阅读我的评论)

这篇关于Python:调用Dict中的有效键/索引时出现KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 14:47