简体   繁体   English

如何根据密钥结尾的内容拆分 dict

[英]How can I split dict based on what the key ends with

I'm trying to split this data_dict我正在尝试拆分此 data_dict

 Timestamp('2022-09-18 06:00:00'): [5.4, 6.0, 6.5, 6.7, 6.9, 7.9, 8.5,7.5, 7.9, 7.8, 7.6, 6.8],
 Timestamp('2022-09-18 18:00:00'): [6.4, 5.7, 4.8, 5.4, 4.7, 4.3],
 Timestamp('2022-09-19 06:00:00'): [3.8],
 Timestamp('2022-09-19 00:00:00'): [4.1, 4.4, 4.3, 3.8, 3.5, 2.8]}

I'm trying to split it into 2 different dicts based on if the key ends with 06:00:00 or not, i wrote the following code:我试图根据密钥是否以 06:00:00 结尾将其拆分为 2 个不同的字典,我编写了以下代码:

def split_morning_night(data_dict):
    mornings = {}
    nights = {} 
    for date, value in data_dict.items():
        if date.endswith("06:00:00"):
            mornings[date] = value
        else:
            nights[date] = value
    return mornings, nights

But im getting the following error when running但是我在运行时遇到以下错误

AttributeError: 'Timestamp' object has no attribute 'endswith'

Is there any other way to solve this problem?有没有其他方法可以解决这个问题? All help appreciated所有帮助表示赞赏

You are using string method with Timestamp in your split_morning_night() method.您在 split_morning_night() 方法中使用带有时间戳的字符串方法。 First typecast it then use it, something like this.首先对它进行类型转换然后使用它,就像这样。

if str(date).endswith("06:00:00"):
    mornings[date] = value
else:
    nights[date] = value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM