Python: 在字典中调用Valid Key/Index时出现KeyError
Python: KeyError when Calling Valid Key/Index in Dict
我有一些 JSON 从 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'}
现在我想访问 'price' 值。
print (result['price'])
这导致 KeyError:
File "C:/Users/Selzier/Documents/Python/temp.py", line 43, in <module>
print (result['price'])
KeyError: 'price'
但是,如果我对(结果)数据执行循环,那么我可以成功打印 i 和 result[i]
for i in result:
if i == "price":
print (i)
print (result[i])
这将打印以下数据:
price
16091.00000000
为什么我在调用时收到 'KeyError':
result['price']
和
result[0]
当我不在 'for i in result' 循环中时?
在 while True
循环中创建一个守卫,就像在 for
循环中一样:
while True:
result = ws.recv()
result = json.loads(result)
if result and 'price' in result:
print(result['price'])
...
(阅读我的评论)
我有一些 JSON 从 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'}
现在我想访问 'price' 值。
print (result['price'])
这导致 KeyError:
File "C:/Users/Selzier/Documents/Python/temp.py", line 43, in <module>
print (result['price'])
KeyError: 'price'
但是,如果我对(结果)数据执行循环,那么我可以成功打印 i 和 result[i]
for i in result:
if i == "price":
print (i)
print (result[i])
这将打印以下数据:
price
16091.00000000
为什么我在调用时收到 'KeyError':
result['price']
和
result[0]
当我不在 'for i in result' 循环中时?
在 while True
循环中创建一个守卫,就像在 for
循环中一样:
while True:
result = ws.recv()
result = json.loads(result)
if result and 'price' in result:
print(result['price'])
...
(阅读我的评论)