python json返回…的列表(双链接dict)?如何搜索关键字获取值?

2024-04-25 23:47:24 发布

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

我的json结构如下所示:

 hrl=
 { "hourly": [
 {
 "FCT":{
       "time":"",
       "cvl": "6am"
       },
  "wind":"brzy",
  "tmp":{
        "brm":"hot",
        "cel":"37"
       },
  "FCT":{
        "time":"",
        "cvl":"7am"
        }
   }
        .... list continues ..
  ]
  }

期望的输出是小时列表(cvl)和tmp

我尝试了各种各样的列表压缩,大致如下: CVL = [ v for k,v in parsed_json["FCT"].iteritems() if k==["cvl"] ]

我似乎无法克服类型错误:例如索引必须是int而不是string,或者我只是过滤掉所有内容并得到一个空数组。你知道吗

怎么回事?你知道吗

(提前感谢)


Tags: json列表time结构tmplistwindhourly
2条回答

你可以试试

CVL = [ v for k,v in parsed_json['hourly'][0]["FCT"].iteritems() if k==["cvl"] ]

相反。你知道吗

hrl = { 
    "hourly": [
        {
            "FCT": {"time":"", "cvl": "6am"},
            "wind": "brzy",
            "tmp": {"brm":"hot", "cel":"37"},
            "FCT": {"time": "", "cvl":"7am"}
        }
        #.... list continues ..
    ]
}

print hrl["hourly"][0]["FCT"]["cvl"]
print hrl["hourly"][0]["tmp"]["cel"]

 output: 
7am
37

仔细想想,您似乎没有发布一个非常好的数据结构表示。如果它看起来像这样,就更有意义了:

hrl = { 
    "hourly": [
        {
            "FCT": {"time":"", "cvl": "6am"},
            "wind": "brzy",
            "tmp": {"brm":"hot", "cel":"37"},
        },

        {
            "FCT": {"time":"", "cvl": "7am"},
            "wind": "windy",
            "tmp": {"brm":"cool", "cel":"20"},
        }
    ]
}

print hrl["hourly"][0]["FCT"]["cvl"]
print hrl["hourly"][0]["tmp"]["cel"]

print hrl["hourly"][1]["FCT"]["cvl"]
print hrl["hourly"][1]["tmp"]["cel"]

 output: 
6am
37
7am
20

results = [
    (_dict["FCT"]["cvl"], _dict["tmp"]["cel"])
    for _dict in hrl["hourly"]
]

print results

 output: 
[('6am', '37'), ('7am', '20')]

hrl[“hourly”]是一个字典数组。在python中,通过使用for-In循环,可以在不使用索引的情况下迭代数组:

for color in ["red", "green", "blue"]:
    print color

 output: 
red
green 
blue

所以您只需要获取数组hrl[“hourly”],并使用for-in循环来选择数组中的每个字典,而不需要整数索引。你知道吗

一个提示:您感兴趣的数据结构的唯一部分是数组,因此您甚至不应该说您的数据结构是dict。只需编写:

arr = hrl["hourly"]

现在您正在处理一个数组,因此不必担心一些嵌套。进一步说,你可以写:

outer_dict = arr[0]
inner_dict_hour = outer_dict["FCT"]
inner_dict_tmp = outer_dict["tmp"]

现在有两个非嵌套字典。例如,获得温度很容易:

 tmp = inner_dict_tmp["cel"]

从这里,您可以替换内部dict tmp等于:

 tmp = inner_dict_tmp      ["cel"]
             |
             v
 tmp = outer_dict["tmp"]   ["cel"]

并替换外螺纹:

 tmp = outer_dict  ["tmp"]["cel"]
           |
           v
 tmp =   arr[0]    ["tmp"]["cel"]

然后替代arr:

 tmp =     arr         [0]["tmp"]["cel"]
            |
            v
 tmp = hrl["hourly']   [0]["tmp"]["cel"]

相关问题 更多 >