【问题标题】:Using an API to get all data from multiple keys of the same name python使用API​​从同名python的多个键中获取所有数据
【发布时间】:2017-05-28 19:16:30
【问题描述】:

我对 API 非常陌生,我正在尝试制作一个 Python 脚本来告诉我我所在城市的白天高峰。我的 API 设置得很好,它输出的数据是这样的:

{
    "SiteRep":{
            "Wx":{
                "Param":[
                {
                    "name":"FDm",
                    "units":"C",
                    "$":"Feels Like Day 
                    Maximum Temperature"
                },
                {
                    "name":"FNm",
                    "units":"C",
                    "$":"Feels Like Night Minimum Temperature"
                },
                {
                    "name":"Dm",
                    "units":"C",
                    "$":"Day Maximum Temperature"
                },
                {
                    "name":"Nm",
                    "units":"C",
                    "$":"Night Minimum Temperature"
                },
                {
                    "name":"Gn",
                    "units":"mph",
                    "$":"Wind Gust Noon"
                },
                {
                    "name":"Gm",
                    "units":"mph",
                    "$":"Wind Gust Midnight"
                },
                {
                    "name":"Hn",
                    "units":"%",
                    "$":"Screen Relative Humidity Noon"
                },
                {
                    "name":"Hm",
                    "units":"%",
                    "$":"Screen Relative Humidity Midnight"
                },
                {
                    "name":"V",
                    "units":"",
                    "$":"Visibility"
                },
                {
                    "name":"D",
                    "units":"compass",
                    "$":"Wind Direction"
                },
                {
                    "name":"S",
                    "units":"mph",
                    "$":"Wind Speed"
                },
                {
                    "name":"U",
                    "units":"",
                    "$":"Max UV Index"
                },
                {
                    "name":"W",
                    "units":"",
                    "$":"Weather Type"
                },
                {
                    "name":"PPd",
                    "units":"%",
                    "$":"Precipitation Probability Day"
                },
                {
                    "name":"PPn",
                    "units":"%",
                    "$":"Precipitation Probability Night"
                }
            ]
            },
                "DV":{
                    "dataDate":"2017-05-28T17:00:00Z",
                    "type":"Forecast",
                    "Location":{
                        "i":"350896",
                        "lat":"50.8371",
                        "lon":"-0.7734",
                        "name":"LONDON",
                        "country":"ENGLAND",
                        "continent":"EUROPE",
                        "elevation":"14.0",
                        "Period":[
                        {
                            "type":"Day",
                            "value":"2017-05-28Z",
                            "Rep":[
                            {
                                "D":"SE",
                                "Gn":"9",
                                "Hn":"66",
                                "PPd":"51",
                                "S":"7",
                                "V":"GO",
                                "Dm":"22",
                                "FDm":"20",
                                "W":"7",
                                "U":"6",
                                "$":"Day"
                            },
                            {
                                "D":"ENE",
                                "Gm":"20",
                                "Hm":"85",
                                "PPn":"42",
                                "S":"9",
                                "V":"VG",
                                "Nm":"16",
                                "FNm":"15",
                                "W":"12",
                                "$":"Night"
                            }
                            ]
                        },
                        {
                            "type":"Day",
                            "value":"2017-05-29Z",
                            "Rep":[
                            {
                                "D":"SW",
                                "Gn":"13",
                                "Hn":"91",
                                "PPd": "59",
                                "S":"9",
                                "V":"GO",
                                "Dm":"18",
                                "FDm":"16",
                                "W":"12",
                                "U":"5",
                                "$":"Day"
                            },
                            {
                                "D":"W",
                                "Gm":"13",
                                "Hm":"93",
                                "PPn":"7",
                                "S":"7",
                                "V":"GO",
                                "Nm":"13",
                                "FNm":"12",
                                "W":"7",
                                "$":"Night"
                            }
                            ]
                        },
                        {
                            "type":"Day",
                            "value":"2017-05-30Z",
                            "Rep":[
                            {
                                "D":"WSW",
                                "Gn":"25",
                                "Hn":"75",
                                "PPd":"9",
                                "S":"13",
                                "V":"VG",
                                "Dm":"18",
                                "FDm":"15",
                                "W":"7",
                                "U":"5",
                                "$":"Day"
                            },
                            {
                                "D":"WNW",
                                "Gm":"13",
                                "Hm":"89",
                                "PPn":"5",
                                "S":"9",
                                "V":"VG",
                                "Nm":"11",
                                "FNm":"10",
                                "W":"0",
                                "$":"Night"
                            }
                            ]
                        },
                        {
                            "type":"Day",
                            "value":"2017-05-31Z",
                            "Rep":[
                            {
                                "D":"SW",
                                "Gn":"13",
                                "Hn":"58",
                                "PPd":"3",
                                "S":"4",
                                "V":"VG",
                                "Dm":"19",
                                "FDm":"18",
                                "W":"1",
                                "U":"7",
                                "$":"Day"
                            },
                            {
                                "D":"NE",
                                "Gm":"9",
                                "Hm":"87",
                                "PPn":"2",
                                "S":"4",
                                "V":"VG",
                                "Nm":"10",
                                "FNm":"9",
                                "W":"0",
                                "$":"Night"
                            }
                            ]
                        },
                        {
                            "type":"Day",
                            "value":"2017-06-01Z",
                            "Rep":[
                            {
                                "D":"ESE",
                                "Gn":"18",
                                "Hn":"56",
                                "PPd":"0",
                                "S":"9",
                                "V":"VG",
                                "Dm":"19",
                                "FDm":"18",
                                "W":"1",
                                "U":"8",
                                "$":"Day"
                            },
                            {
                                "D":"E",
                                "Gm":"13",
                                "Hm":"80",
                                "PPn":"1",
                                "S":"9",
                                "V":"VG",
                                "Nm":"11",
                                "FNm":"9",
                                "W":"0",
                                "$":"Night"
                            }
                            ]
                        }
                        ]
                    }
                }
        }
    }

问题是我想打印出所有白天的高单位,这些是字典中的 Dm 键,但我无法将所有单独字典中的键对应的所有数据收集到一个列表中(或其他任何东西) .以任何数据类型收集它们的任何帮助都会非常有帮助。我的目标是打印出日期与它们对应的白天高点。

感谢您阅读(和帮助), API 的菜鸟

附:如果需要,这是我用来获取信息的脚本的副本,它使用 Met Office(这是英国的天气预报网站)API:

import urllib.request, json, codecs

url = 'Insert API here'
json_obj = urllib.request.urlopen(url)
reader = codecs.getreader("utf-8")
data = json.load(reader(json_obj))
print (data)

【问题讨论】:

    标签: python python-3.x api dictionary weather


    【解决方案1】:

    据我所知,您的数据嵌套在 SiteRep -> DV -> Location -> Period 列表中,特别是它的 Rep 元素,因此您只需遍历它们,获取 Dm 值并存储在列表,存储为字典,键为每个句点的value。比如:

    dms = {}  # use this dict for storage
    for period in data["SiteRep"]["DV"]["Location"]["Period"]:  # loop through periods
        # use Period's 'value' as a key; pick up Dm values and store them as value, as a list
        dms[period["value"]] = [v["Dm"] for v in period["Rep"] if "Dm" in v]
    
    print(dms)
    # {'2017-05-29Z': ['18'], '2017-05-28Z': ['22'], '2017-05-30Z': ['18'],
    # '2017-05-31Z': ['19'], '2017-06-01Z': ['19']}
    

    如果Dm 永远不会出现在Rep 的第二个列表元素中(因此只有单个值),您可以将其进一步简化为:

    dms = {}  # use this dict for storage
    for period in data["SiteRep"]["DV"]["Location"]["Period"]:  # loop through periods
        # use Period's 'value' as a key; pick up Dm values and store them as value, as a list
        dms[period["value"]] = period["Rep"][0]["Dm"]
    
    print(dms)
    # {'2017-05-29Z': '18', '2017-05-28Z': '22', '2017-05-30Z': '18',
    # '2017-05-31Z': '19', '2017-06-01Z': '19'}
    

    甚至:

    dms = {p["value"]: p["Rep"][0]["Dm"] for p in data["SiteRep"]["DV"]["Location"]["Period"]}
    
    print(dms)
    # {'2017-05-29Z': '18', '2017-05-28Z': '22', '2017-05-30Z': '18',
    # '2017-05-31Z': '19', '2017-06-01Z': '19'}
    

    这是最快的,但它变得难以阅读......

    【讨论】:

      【解决方案2】:

      查看您的数据,我可以看到它包含:

      • 只有一个键的字典,SiteRep 包含
      • 有成员的字典Wx & DV
        • Wx 是一键字典,Param
        • Param 是一个字典列表,每个字典都包含以下成员:$name & units 其中$ 是描述性文本。 我个人会尝试将其重组为以名称为键的字典字典

      data['SiteRep']['Wx']['Param'][0] ==> { '$': 'Feels Like Day Maximum Temperature', 'name': 'FDm', 'units': 'C'}

      但这可以映射为:

      params = {i['name']:(i['$'], i['units']) for i in data['SiteRep']['Wx']['Param']}
      
      • DV 是带有dataDatetypeLocation 键的字典
        • `DV['dataDate'] 只是 '2017-05-28T17:00:00Z' 即生成数据的时间。
        • 'DV['location']is a dictionary with members'i', 'lat', 'lon', 'name', 'country', 'continent', 'elevation', 'Period' .
        • DV['location']['Period'] 长度为 5 的列表建议进行 5 天预测
        • 每个条目都是一个带有键 'type', 'value', 'Rep' 的字典,其中类型和值分别是“日”和日期。
        • 每个DV['location']['Period'][n]['Rep'] 是一个包含 2 个字典的列表,每个字典都有成员 'D', 'Gn', 'Hn', 'PPd', 'S', 'V', 'Dm', 'FDm', 'W', 'U', '$',这恰好是 data['Wx']['Param'] 中的名称,$ 除外,它是DayNight

      所以基本上你需要的所有数据都在那里,你只需要深入研究一下。

      使用了上面params 的映射和data['SiteRep']['DV']['Rep'][0] 的局部变量D0 我可以打印:

      print('Date:', d0['value'])
      for f in d0['Rep']:
          print(f['$'])
          for k,v in f.items():
              if k in params:
                  print(params[k][0], v, params[k][1])
      

      得到:

      Date: 2017-05-28Z
      Day                                               
      Wind Direction SE compass                         
      Wind Gust Noon 9 mph                              
      Screen Relative Humidity Noon 66 %                
      Precipitation Probability Day 51 %                
      Wind Speed 7 mph                                  
      Visibility GO                                     
      Day Maximum Temperature 22 C                      
      Feels Like Day Maximum Temperature 20 C           
      Weather Type 7                                    
      Max UV Index 6                                    
      Night                                             
      Wind Direction ENE compass                        
      Wind Gust Midnight 20 mph                         
      Screen Relative Humidity Midnight 85 %            
      Precipitation Probability Night 42 %              
      Wind Speed 9 mph                                  
      Visibility VG                                     
      Night Minimum Temperature 16 C                    
      Feels Like Night Minimum Temperature 15 C         
      Weather Type 12                                   
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-31
        • 2014-04-10
        • 1970-01-01
        • 1970-01-01
        • 2016-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多