简体   繁体   English

访问 Python 字典中的键时出错

[英]Error accessing keys in Python dictionary

I'm doing a request with the following data body and when I try to access users["primary"] it errors out.我正在使用以下数据主体发出请求,当我尝试访问users["primary"]它出错了。 printing the value for the users key gives me ['secondaryIds', 'primary'] which is weird.打印users键的值给了我['secondaryIds', 'primary']这很奇怪。 Why is this an array rather than a dictionary.为什么这是一个数组而不是字典。

data = {
    "users": {
        "primary": "a",
        "secondaryIds": ["b", "c", "a"]
    }
}

r = requests.post(url, data=data)

In my server code, before I get into the function where I'm trying to unpack the data, I do在我的服务器代码中,在我尝试解压缩数据的功能之前,我会

body = event["body"]
parameters = urllib.parse.parse_qs(body)
users = parameters["users"]

update_users(users) // right now this function just prints `users` and returns a 200

Confused as to what's going on here and would love a little help.对这里发生的事情感到困惑,希望得到一些帮助。 Thanks!谢谢!

Unless you're setting除非你设置

users = data['users']

that is a correctly raised NameError .这是一个正确引发的NameError

I think you want data['users']['primary']我想你想要data['users']['primary']


Based on the updates to your question, this is likely happening because you're trying to parse a dictionary as a querystring.根据您的问题的更新,这很可能发生,因为您正在尝试将字典解析为查询字符串。 If you omit the line如果省略该行

parameters = urllib.parse.parse_qs(body)

you should be able to access the users list with您应该能够访问users列表

body['users']

or with或与

json.loads(body)['user']

I'm unclear on how your event returns the request body (if it parses it as json before returning or not)我不清楚您的event如何返回请求正文(是否在返回之前将其解析为 json)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM