【问题标题】:How to get a particular key value inside dict [closed]如何在dict中获取特定的键值[关闭]
【发布时间】:2021-07-03 11:18:33
【问题描述】:
{
    "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"
    }
}

给出一个解决方案,获取''text''键对应的值

【问题讨论】:

标签: python python-3.x dictionary


【解决方案1】:

您可以使用下标运算符 ([]) 访问 dict 中的特定值。如果键引用的值本身是一个字典,您可以继续在其上使用下标运算符。在你的情况下:

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

【讨论】:

    【解决方案2】:

    您可以使用[] 运算符。

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

    例子:

    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"
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多