如何访问字典中的特定元素?

2024-06-11 16:39:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本有一张单子的字典,单子里有两本字典:

dict: {
 "weather":[
   {"id": 701, "main": "Mist", "description": "mist"},
   {"id": 300, "main": "Drizzle", "description": "light intensity drizzle"}
 ]
}

我想访问词典中的light intensity drizzle,我该怎么做?你知道吗

我知道我必须做dict[0]。。。但之后我就被困住了


Tags: id字典maindescriptiondict词典单子light
3条回答

在JavaScript中:

dict.weather[1].description

在Python中:

dictVar["weather"][1]["description"]

(Python需要将dict更改为dictVar,因为dict是保留的)

解决问题

您可以遵循下一个逻辑:

  1. 您正在处理一个名为dict的对象。你知道吗
  2. 它有一个名为wheather的键,该键分配了一个数组。你知道吗
  3. 该数组是一个对象数组,每个对象中都有不同的键。你知道吗

在Javascript中

为了在Javascript的对象/字典中查找分配给键的值,您必须连接父项的名称adot和嵌套在父项中的键的名称:

dict.wheather

下一步是进入数组。为此,必须将索引放在方括号内:

dict.wheather[1]

注意数组中的第一个元素有0作为索引。你知道吗

接下来重复第一步,写一个和要查找的键。你知道吗

dict.wheather[1].description

然后,记住将它赋给一个变量,并通过consoleloggit打印它。你知道吗

var myVariable = dict.wheather[1].description;
console.log(myVariable);

在Python中

您可以使用相同的逻辑,但需要更改键“dict”,因为它是python本身保留的字。在本例中,我将用dictionary而不是dict向您展示示例。另外,我打印时没有指定一个变量的键。 此外,您还需要稍微更改sintax:

print(dictionary["weather"][1]["description"])

希望对你有用:)

有关更多资源,请检查以下内容:

抱歉,如果我的英语很好:)

您有一个具有一个键("weather")的字典/映射,该键的值为列表/数组,第二个索引具有所需的描述字段,相应地索引到字典/映射中:

对于Python:

d = {
        "weather": [
            {
                "id": 701,
                "main": "Mist",
                "description": "mist"
            },
            {
                "id": 300,
                "main": "Drizzle",
                "description": "light intensity drizzle"
            }
        ]
    }

drizzle_string = d["weather"][1]["description"]
print(drizzle_string)

输出:

light intensity drizzle

对于Javascript:

相关问题 更多 >