【问题标题】:Python: KeyError when Calling Valid Key/Index in DictPython:在字典中调用有效键/索引时出现 KeyError
【发布时间】: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'

但是,如果我对(结果)数据执行循环,那么我可以成功打印 iresult[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


【解决方案1】:

while True 循环中创建一个守卫,就像在for 循环中一样:

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

(阅读我的评论)

【讨论】:

  • 谢谢 sKwa,已修复!我试图检查字典的 Len() 是否 > 0,但这也不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2013-03-13
  • 2020-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多