首先,您对嵌套字典的描述和示例是正确的。但是,我并不完全清楚您显示的数据是什么。在 api 的示例输出中,代码段以逗号结尾,您应该对其进行编辑,以便人们可以看到格式正确的整个输出。就目前的示例而言,它在 python 中没有有效的语法。如果实际的 api 输出与您显示的完全一样,那么看起来数据是 json 格式而不是 python 格式。如果您想了解如何在 python 中解析 json 数据,请查看此答案 Deserialize a json string to an object in python 。
我将假设您从 API 获得的数据看起来像这样(我删除了逗号并添加了一个后括号,并用花括号将集合括起来以使其有效 python,我还将它分配给一个变量,所以我们可以通过键访问它的值):
api_output = {
"Brands": {[
{
"brand_id": "brand1",
"brand_display": "Brand One",
"brand_is_common": "No",
"brand_country": "UK"
},
{
"brand_id": "brand2",
"brand_display": "BRand Two",
"brand_is_common": "Yes",
"brand_country": "USA"
},
{
"brand_id": "brand3",
"brand_display": "Brand Three",
"brand_is_common": "No",
"brand_country": "UK"
}]}
}
我们正在查看具有以下结构的字典:
example_dict = {
"example_key":{
[ #the square brackets denote a list
{"sub_key":sub_value,"sub_key0":sub_value0},
{"sub_key":sub_value} #these dicts are stored in the list
]
}
}
您的直觉是正确的,api 没有返回嵌套字典。数据格式似乎是一个带有字符串键的字典,其值是一个列表,其中包含一组字典。
回到您的示例,我们需要同时导航列表和字典。要访问列表中的值,我们通过索引,访问字典中的值,我们通过键。由于字典列表存储为另一个字典的值,我们使用它的相应键来访问列表。
list_of_brands = api_output["Brands"] #assign the value of "Brands" to a variable
#we can check the value type (not needed but useful for understanding whats going on)
type(list_of_brands)
#out: list
现在我们需要通过索引遍历列表以获取它包含的字典,然后假设要检查每个字典中的每个键,我们将遍历字典的键并使用值做一些事情:
for brand in list_of_brands: # for each dictionary in the list
for key in brand: # loop through the keys of the current dict,
print(" key: " + key + "\n value: " + brand[key]) #prints the key and its value
总而言之,代码如下所示:
api_output = {
"Brands": {[
{
"brand_id": "brand1",
"brand_display": "Brand One",
"brand_is_common": "No",
"brand_country": "UK"
},
{
"brand_id": "brand2",
"brand_display": "BRand Two",
"brand_is_common": "Yes",
"brand_country": "USA"
},
{
"brand_id": "brand3",
"brand_display": "Brand Three",
"brand_is_common": "No",
"brand_country": "UK"
}]}
}
for brand in list_of_brands: # for each dictionary in the list
for key in brand: # loop through the keys of the current dict,
print(" key: " + key + "\n value: " + brand[key]) #prints the key and its value
希望这可以帮助您更好地了解正在发生的事情!