尝试访问字典索引0时发生Python KeyError:dict [0] [英] Python KeyError when trying to access Dictionary Index 0: dict[0]

查看:383
本文介绍了尝试访问字典索引0时发生Python KeyError:dict [0]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将此问题移至新帖子:

I've moved this question to a new post: Python: KeyError when Calling Valid Key/Index in Dict

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

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])

这将打印"Valid_Key"和"Some_value".
但是,如果我尝试通过键名或索引来访问它,则会收到"KeyError"消息.

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])

这将导致:
KeyError:0

This will result in:
KeyError: 0

print (result["Valid_Key"])

这将导致:
KeyError:"Valid_Key"

This will result in:
KeyError: 'Valid_Key'

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

How can I access dictionary data by index or key in Python?

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

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

Example with KeyError: https://s17.postimg.org/t9r95mxvz/Key_Error.jpg

推荐答案

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

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'

在True循环中创建防护,例如在for循环中

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'])
    ...

感谢sKwa,在这里回答: Python:在Dict中调用有效键/索引时出现KeyError

Thanks to sKwa, answered here: Python: KeyError when Calling Valid Key/Index in Dict

这篇关于尝试访问字典索引0时发生Python KeyError:dict [0]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆