【问题标题】:Python KeyError when trying to access Dictionary Index 0: dict[0]尝试访问字典索引0时的Python KeyError:dict [0]
【发布时间】:2018-06-15 01:31:00
【问题描述】:

编辑:我已将此问题移至新帖子:Python: KeyError when Calling Valid Key/Index in Dict

我通过 websocket 成功接收了一些格式正确的 JSON 数据:

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

我可以像这样遍历字典:

    for i in result:
        print (i)
        print (result[i])

这将打印“Valid_Key”和“Some_value”。
但是,如果我尝试通过键名或索引来访问它,我将收到“KeyError”。

print (result[0])

这将导致:
KeyError: 0

print (result["Valid_Key"])

这将导致:
KeyError: 'Valid_Key'

如何在 Python 中通过索引或键访问字典数据?

没有错误的示例: https://s17.postimg.org/e11brl99r/Success.jpg

KeyError 示例: https://s17.postimg.org/t9r95mxvz/Key_Error.jpg

【问题讨论】:

  • 不能索引字典,因为它们没有特定的顺序。但是,您可以索引一个列表,其中字典项目已被转换到。在你的情况下,那将是list(result.items())[0](或list(result.values())[0])。但是,请注意,字典中没有 firstnth 项的概念。所以上面的代码可以为相同的输入产生不同的输出。您已被警告 ;)
  • 其实Python's documentation保证如果在迭代之间没有进行任何更改,它们将直接对应。
  • @DanielRoseman 如果您关闭脚本并再次加载它会怎样?还是再次收到完全相同的json 字典?
  • 如果result dict 的键为"Valid_Key",那么result["Valid_Key"] 应该为您提供与该键关联的值。也许转换后的 JSON 对象并不完全是您认为的那样。你能告诉我们一个例子result,它给出了你所说的错误吗?
  • 我仍然不知道你的数据是什么样的。请参阅Why may I not upload images of code on SO when asking a question?

标签: python json csv dictionary keyerror


【解决方案1】:

while True 中的问题:在第一次迭代中,您得到的结果为 15800.0,但在第二次迭代中,您的字典不包含 key = 'price'

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

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

感谢 sKwa,在这里回答: Python: KeyError when Calling Valid Key/Index in Dict

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多