目录
- 1 key是时间字符串类型
-
- 1.1 问题
- 1.2 解决办法
- 2 key是datetime类型
-
- 2.1 问题
- 2.2 解决方案
1 key是时间字符串类型
1.1 问题
当字典的key是时间字符串类型,如下
time_dict = {‘2021-05-18’: 119,
‘2021-06-05’: 119,
‘2020-12-10’: 116,
‘2021-04-19’: 110,
‘2020-12-04’: 108,
‘2021-04-13’: 106,
‘2020-12-08’: 106,
‘2020-09-12’: 103,
‘2021-05-14’: 101,
‘2021-05-08’: 100,
‘2021-01-09’: 99,
‘2020-12-09’: 99,
‘2021-06-25’: 99,
‘2021-05-28’: 99}
想要实现,根据key进行排序。
1.2 解决办法
({k: v
for k, v in sorted(
time_dict.items(),
key=lambda x: time.datetime.strptime(x[0], '%Y-%m-%d')
)
})
输出
{‘2020-01-01’: 7,
‘2020-01-02’: 13,
‘2020-01-03’: 6,
‘2020-01-04’: 6,
‘2020-01-05’: 11,
‘2020-01-06’: 8,
‘2020-01-07’: 16,
‘2020-01-08’: 15,
‘2020-01-09’: 21,
‘2020-01-10’: 28,
‘2020-01-11’: 15,
‘2020-01-12’: 17,
‘2020-01-13’: 10,
‘2020-01-14’: 15,
‘2020-01-15’: 7}
2 key是datetime类型
2.1 问题
字典的key是datetime类型的Timestamp,想要对其字典中的时间排序
time_dict = {Timestamp(‘2021-05-18 00:00:00’): 119,
Timestamp(‘2021-06-05 00:00:00’): 119,
Timestamp(‘2020-12-10 00:00:00’): 116,
Timestamp(‘2021-04-19 00:00:00’): 110,
Timestamp(‘2020-12-04 00:00:00’): 108,
Timestamp(‘2020-12-08 00:00:00’): 106,
Timestamp(‘2021-04-13 00:00:00’): 106,
Timestamp(‘2020-09-12 00:00:00’): 103,
Timestamp(‘2021-05-14 00:00:00’): 101,
Timestamp(‘2021-05-08 00:00:00’): 100,
Timestamp(‘2021-05-28 00:00:00’): 99,
Timestamp(‘2021-06-25 00:00:00’): 99,
Timestamp(‘2020-12-09 00:00:00’): 99,
Timestamp(‘2021-01-09 00:00:00’): 99,
Timestamp(‘2021-04-09 00:00:00’): 98,
Timestamp(‘2020-11-06 00:00:00’): 98}
2.2 解决方案
sorted(time_dict.items(),key=lambda x:x[0])
输出
[(Timestamp(‘2020-01-01 00:00:00’), 7),
(Timestamp(‘2020-01-02 00:00:00’), 13),
(Timestamp(‘2020-01-03 00:00:00’), 6),
(Timestamp(‘2020-01-04 00:00:00’), 6),
(Timestamp(‘2020-01-05 00:00:00’), 11),
(Timestamp(‘2020-01-06 00:00:00’), 8),
(Timestamp(‘2020-01-07 00:00:00’), 16),
(Timestamp(‘2020-01-08 00:00:00’), 15),
(Timestamp(‘2020-01-09 00:00:00’), 21),
(Timestamp(‘2020-01-10 00:00:00’), 28),
(Timestamp(‘2020-01-11 00:00:00’), 15),
(Timestamp(‘2020-01-12 00:00:00’), 17),
(Timestamp(‘2020-01-13 00:00:00’), 10),
(Timestamp(‘2020-01-14 00:00:00’), 15),
(Timestamp(‘2020-01-15 00:00:00’), 7)]