如何在dict中获取特定的键值

2024-07-07 05:37:02 发布

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

{
    "id": "3xj1z9mKjaI",
    "title": "\u0d36\u0d3e\u0d2a \u0d35\u0d3e\u0d15\u0d4d\u0d15\u0d4d \u0d2a\u0d31\u0d1e\u0d4d\u0d1e\u0d3f\u0d1f\u0d4d\u0d1f\u0d41\u0d33\u0d4d\u0d33 \u0d09\u0d2e\u0d4d\u0d2e\u0d2e\u0d3e\u0d30\u0d4d\u200d \u0d05\u0d31\u0d3f\u0d2f\u0d23\u0d02 | \u0d15\u0d30\u0d1e\u0d4d\u0d1e\u0d4d \u0d2a\u0d4b\u0d15\u0d41\u0d02 | makkal mathapithakkal | marhaba media",
    "viewCount": {
        "text": "163509"
    }
}

给出一个解决方案以获取与“文本”键对应的值


Tags: idtitleu0d4du0d30u0d2eu0d3eu0d15u0d1f
3条回答

您可以使用[]运算符

通过在字典上使用它,它将返回附加到该键的值,方法也会这样做。这意味着您可以获取返回值并将其放入变量中,在方法中使用它,等等

例如:

dct = {
    "my_first_key": "my_first_value",
    "my_second_key": "my_second_value"
}

my_var = dct["my_first_key"] # This variable will contain the string : "my_first_value"

然后,您可以将其复制到“内部字典”:

dct = {
    "my_first_key": "my_first_value",
    "my_second_key": "my_second_value",
    "my_second_dict": {
        "my_third_key": "my_third_value"
    }
}

my_var = dct["my_first_key"] # This variable will contain the string : "my_first_value"

my_final_var = dct["my_second_dict"]["my_third_key"] # This variable will contain the string : "my_third_value"

我建议你看看官方的python documentation,对于你的问题,工作代码是:

print(name_of_your_dictionary['viewCount']['text'])

您可以使用下标运算符([])访问dict中的特定值。如果keys引用的值是dict本身,则可以继续对其使用下标运算符。就你而言:

text_value = my_dict['viewCount']['text']

相关问题 更多 >