首页 > 解决方案 > 使用python中的日期时间键返回字典中日期时间键的值

问题描述

我有一本看起来像这样的字典 -

{
        "2017-04-21T08:00:00-04:00": {
            "visibility": {
            "prevailing": 10.0,
            "units": "SM"
        },
        "wind": {
            "speed": 13.0,
            "crosswind": 2.0,
            "units": "KT"
        },
        "temperature": {
            "value": 13.9,
            "units": "C"
        },
        "sky": [
            {
                "cover": "clouds",
                "type": "broken",
                "height": 700.0,
                "units": "FT"
            }
        ],
        "code": "201704211056Z"
    },
    "2017-04-21T07:00:00-04:00": {
        "visibility": {
            "prevailing": 10.0,
            "units": "SM"
        },
        "wind": {
            "speed": 13.0,
            "crosswind": 2.0,
            "units": "KT"
        },
        "temperature": {
            "value": 13.9,
            "units": "C"
        },
        "sky": [
            {
                "type": "overcast",
                "height": 700.0,
                "units": "FT"
            }
        ],
        "code": "201704210956Z"
    }
    ...
}

在上述字典的键中搜索给定的日期时间后,我需要返回它的值,该值也是天气报告的字典。我在 return 语句上遇到语法错误。我的代码是 -

tOff = takeoff.isoformat() #---> takeoff is the supplied datetime value to search for in the 
                                 dictionary

if tOff in weather.keys():
    return weather[tOff]. #---> I get a syntax error on this statement
else:
    #tm = datetime.takeoff.timetz()
    for t in weather.keys():
        if max(weather[t]) < tOff:
            return weather[t]
        else:
            return

请帮助提供一些关于我为什么会出现语法错误以及如何解决它的指导

标签: python

解决方案


你有一个额外的 . 在这。

if tOff in weather.keys():
    return weather[tOff]. #---> I get a syntax error on this statement

您应该删除额外的 . 请参阅下面的固定代码

if tOff in weather.keys():
    return weather[tOff] #---> removed . from the return statement

推荐阅读