[英]KeyError in Python, even though the key exists
I have been scratching my head on this for a few days now and cannot seem to find a solution that works online for my problem.几天来,我一直在为此摸不着头脑,似乎找不到可以在线解决我的问题的解决方案。 I am trying to access data on zendesk and go through the pagination.
我正在尝试通过分页访问 zendesk 和 go 上的数据。 For some reason, I am getting a KeyError, even though I can see that the key does exist.
出于某种原因,我得到了一个 KeyError,即使我可以看到该密钥确实存在。 Here is my code:
这是我的代码:
data_users2 = [[]]
while url_users:
users_pagination = requests.get(url_users,auth=(user, pwd))
data_user_page = json.loads(users_pagination.text)
print (data_user_page.keys())
for user in data_user_page['users']:
data_users2.append(user)
url = data_user_page['next_page']
Here is the output:这是 output:
dict_keys(['users', 'next_page', 'previous_page', 'count'])
dict_keys(['error'])
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-22-fab95d95ddeb> in <module>
6 data_user_page = json.loads(users_pagination.text)
7 print (data_user_page.keys())
----> 8 for user in data_user_page["users"]:
9 data_users2.append(user)
10 url = data_user_page["next_page"]
KeyError: 'users'
As you can see, users does exist.如您所见,用户确实存在。 same thing happens if I try to print the next_page, I get a KeyError for next_page.
如果我尝试打印 next_page,也会发生同样的事情,我得到 next_page 的 KeyError。
Any help would be appreciated !任何帮助,将不胜感激 ! Thanks!
谢谢!
Your code is failing in its second iteration of the loop, in that moment your keys in data_user_page
are just "error" as you can see in the output you have pasted您的代码在循环的第二次迭代中失败,在那一刻,您在
data_user_page
中的键只是“错误”,正如您在粘贴的 output 中看到的那样
dict_keys(['users', 'next_page', 'previous_page', 'count']) <----- FIRST ITERATION
dict_keys(['error']) <---- SECOND ITERATION, THEREFORE, YOUR KEY DOES NOT EXISTS
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-22-fab95d95ddeb> in <module>
6 data_user_page = json.loads(users_pagination.text)
7 print (data_user_page.keys())
----> 8 for user in data_user_page["users"]:
9 data_users2.append(user)
10 url = data_user_page["next_page"]
KeyError: 'users'
EDIT: This could be due to the fact that you are saving the next url in a variable called url
not url_users
编辑:这可能是因为您将下一个 url 保存在名为
url
的变量中,而不是url_users
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.