【发布时间】:2018-01-05 16:11:06
【问题描述】:
我有一些从 websocket 中提取的 JSON 数据:
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' 循环内时?
【问题讨论】:
-
print (result['price'])使用您在上面发布的示例字典对我来说很好。 -
您需要展示演示问题的完整代码。
-
您确定在无限循环的每个循环中始终获得有效的“结果”值吗?这可能是一个线索,因为如果在您的一次迭代中结果无效,那么您的密钥迭代当然不会失败,但直接访问会失败。
-
while True中的问题:在第一次迭代时,您得到了结果15800.0,但在第二次迭代中,您的字典不包含key = 'price'。 -
你应该修复your earlier question而不是开始一个新的。
标签: python json dictionary keyerror