Python: KeyError when Calling Valid Key/Index in Dict

有些话、适合烂在心里 提交于 2019-12-24 20:19:21

问题


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

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

Here is Print(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'}

Now I want to access the 'price' value.

print (result['price'])

This results with a KeyError:

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

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])

Which will print the following data:

price
16091.00000000

Why do I get a 'KeyError' when calling:

result['price']

AND

result[0]

When I'm not inside of the 'for i in result' loop?


回答1:


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'])
    ...

(read my comment)



来源:https://stackoverflow.com/questions/48117272/python-keyerror-when-calling-valid-key-index-in-dict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!