在python中访问嵌套字典
我试图从下面的字典中访问创建者的值以及其他值,如描述和电子邮件。在python中访问嵌套字典
我试图将其转换为json然后访问密钥。但它没有奏效。迭代整个词典并获取所有键值的唯一方法。
任何建议将是伟大的!
{
"description": xxx,
"email": [email protected],
"creator": {
"data": [
{
"name": "john"
"id": "123"
},
{
"name": "victor"
"id" : "345"
}
]
}
假设你有任何深度的字典。
dict = {"description": xxx, ...
可以通过指定的键时,会从字典中的项目:
desc = dict["description"] # returns "xxx"
您可以递归做到这一点:
name = dict["creator"]["data"] # returns list of people [{"name": "john", "id": "123"}, {"name": "victor", "id": "345"}]
name = dict["creator"]["data"][0] # returns the first item in the list {"name": "john", "id": "123"}
name = dict["creator"]["data"][0]["name"] # returns "john"
这适用于非嵌套字典,但不适用于嵌套字典! – user3447653
@ user3447653:我编辑了我的答案。这是否更清晰?如果不是,你究竟想达到什么目的? –
你可能想更详细地解释一下这里发生了什么。 – Gassa
dict["description"]
将返回'xxx'
dict["creator"]['data']
将返回[{"name": "john","id": "123"},{"name": "victor","id" : "345"}]
dict["creator"]['data'][1]["name"]
将返回"john"
哪里dict
是你的字典
你应该表现出你尝试和解释什么是“没有工作”需要。 – Sayse
它不会是字典[“创建者”] [“数据”]? – Jerrybibo