如何根据日期范围从字典列表中过滤出子字典

我需要根据日期范围从字典列表中过滤出子字典


这是我的清单:


[{'5-jan-2019': '34'}, {'10-jan-2019': '34'}, {'21-jan-2019': '12'}, {'25-jan-2019': '34'} , {'5-feb-2019': '34'}]

我需要过滤掉一个日期范围内的所有子词典


from_date-'5-jan-2019' and  to_date-'25-jan-2019'

并将其添加到新字典中


预期结果


{

    '5-jan-2019': '34',

    '10-jan-2019': '34',

    '21-jan-2019': '12',

    '25-jan-2019': '34'

}


慕码人2483693
浏览 122回答 2
2回答

慕森卡

您希望 datetime.strptime 将字符串转换为 datetime 对象,然后您可以将它们相互比较。from datetime import datetimelst = [&nbsp; &nbsp; {'5-jan-2019': '34'},&nbsp; &nbsp; {'10-jan-2019': '34'},&nbsp; &nbsp; {'21-jan-2019': '12'},&nbsp; &nbsp; {'25-jan-2019': '34'},&nbsp; &nbsp; {'5-feb-2019': '34'},&nbsp; &nbsp; ]dt_from_str = lambda dt: datetime.strptime(dt, '%d-%b-%Y')start_date = dt_from_str('5-jan-2019')end_date = dt_from_str('25-jan-2019')new_dict = {}for sub_dict in lst:&nbsp; &nbsp; for key, val in sub_dict.items():&nbsp; &nbsp; &nbsp; &nbsp; if start_date <= dt_from_str(key) <= end_date:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new_dict[key] = valprint(new_dict)输出:{&nbsp; &nbsp; '5-jan-2019': '34',&nbsp; &nbsp; '10-jan-2019': '34',&nbsp; &nbsp; '21-jan-2019': '12',&nbsp; &nbsp; '25-jan-2019': '34',}

慕仙森

您可以使用该datetime模块来利用对象的内置比较方法(__lt__等)datatime.datetime:import datetimedata = [{'5-jan-2019': '34'}, {'10-jan-2019': '34'}, {'21-jan-2019': '12'}, {'25-jan-2019': '34'} , {'5-feb-2019': '34'}]start, end = '5-jan-2019', '25-jan-2019'def d_form(d):&nbsp; &nbsp;months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']&nbsp; &nbsp;_d, _m, _y = d.split('-')&nbsp; &nbsp;return datetime.datetime(int(_y), months.index(_m)+1, int(_d))start, end = d_form(start), d_form(end)final_result = [i for i in data if start <= d_form(list(i.keys())[0]) <= end]输出:[{'5-jan-2019': '34'},&nbsp;&nbsp;{'10-jan-2019': '34'},&nbsp;&nbsp;{'21-jan-2019': '12'},&nbsp;&nbsp;{'25-jan-2019': '34'}]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python