I'm successfully receiving some properly formatted JSON data via websocket:
while True:
result = ws.recv()
result = json.loads(result)
I can loop through the dictionary like this:
for i in result:
print (i)
print (result[i])
This will print "Valid_Key" and "Some_value".
However, if I try to access this by key name or index, I will receive a "KeyError".
print (result[0])
This will result in:
KeyError: 0
print (result["Valid_Key"])
This will result in:
KeyError: 'Valid_Key'
How can I access dictionary data by index or key in Python?
解决方案
The problem in while True: on first iteration you got a result 15800.0, but on second iteration your dictionary do not contains key = 'price'
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'])
...