【问题标题】:How to get specific value in dictionary python?如何在字典python中获取特定值?
【发布时间】:2016-11-20 21:54:34
【问题描述】:

我有字典,

"countries":{
    "98":{
        "uid":98,
        "title":"Switzerland"
        }
}    

我想使用 json 解码方法获取“title”的值。

注意:“98”的值是动态的,所以每次都会变化。

我怎样才能做到这一点?

【问题讨论】:

  • 如果你有一个变量x 持有"98" 应该代表的任何东西,那么countries[x]["title"] 或者可能mydict["countries"][x]["title"] 如果这就是你所拥有的。如果不是,那么我无法说出你在问什么。
  • 能否提供json解码方式的代码?
  • 你试过什么? (另外,您发布的 sn-p 不是真正有效的 JSON)
  • [item['title'] for item in dictName['countries']]
  • 如果你有一个真正的 Python 字典,那么你不需要 json 解码。如果您有 JSON 文件或字符串,那么您需要在问题中明确说明。在您解决这个歧义之前,您的问题是无法回答的。

标签: python json dictionary


【解决方案1】:

如果你的意思是你有几个像98 这样的字段,但它们都包含一个标题,你可以这样做:

titles = list()
for k in my_dict["countries"].keys():

    if my_dict["countries"][k].has_key("title"):

        titles.append(my_dict["countries"][k]["title"])

或者,如 cmets 中所建议的那样

try:
    titles = [item['title'] for item in dictName['countries']]
except KeyError:
    print("no countries/title")

【讨论】:

    【解决方案2】:

    我将假设您提供的“字典”是 JSON 格式的字符串,并且您希望将其解码为 Python 对象(字典)然后访问标题。

    如果是这样,json 模块就是你的朋友! 文档:https://docs.python.org/3/library/json.html

    伪代码

    import json
    
    # This is your JSON string
    json_str = "......."
    
    # This could be a dictionary, depending on the structure of the input JSON string
    countries = json.loads(json_str)
    
    # access!
    target_uid = "98"
    
    # This should print Switzerland
    print(countries["countries"][target_uid]["title"])
    

    【讨论】:

    • 根据数据target_uid必须是字符串。
    • @Matthias 不错。更新。谢谢!
    猜你喜欢
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多