如何在Python中按时间顺序排序含列表的嵌套字典?
按时间顺序排序嵌套字典中的月份
针对你给出的嵌套字典,要按月份时间顺序排序内层字典,可以通过以下Python代码实现:
步骤说明
- 先定义月份顺序参照列表,对应一年中月份的先后顺序,以此作为排序依据。
- 遍历外层字典的每个年份条目,对其内层的月份键,按照参照列表的顺序排序,再重新构建有序字典(Python 3.7及以上版本的字典默认保留插入顺序)。
代码实现
import calendar # 输入的嵌套字典 input_dict = { 2024: { 'Jul': ['Rate', 'Hours', 'Cost'], 'Jan': ['Rate', 'Hours', 'Cost'], 'Feb': ['Rate', 'Hours', 'Cost'], 'Mar': ['Rate', 'Hours', 'Cost'], 'Apr': ['Rate', 'Hours', 'Cost'], 'May': ['Rate', 'Hours', 'Cost'], 'Jun': ['Rate', 'Hours', 'Cost'] } } # 获取标准的三字母月份缩写列表(Jan到Dec) month_order = list(calendar.month_abbr)[1:] # 索引0是空字符串,从1开始取有效月份 # 处理嵌套字典:对每个年份下的月份按顺序排序 sorted_dict = {} for year, months in input_dict.items(): # 按month_order中的顺序排序月份键,生成新的有序字典 sorted_months = dict(sorted(months.items(), key=lambda x: month_order.index(x[0]))) sorted_dict[year] = sorted_months # 输出结果 print(sorted_dict)
执行结果
运行后会得到你期望的有序嵌套字典:
{2024: { 'Jan': ['Rate', 'Hours', 'Cost'], 'Feb': ['Rate', 'Hours', 'Cost'], 'Mar': ['Rate', 'Hours', 'Cost'], 'Apr': ['Rate', 'Hours', 'Cost'], 'May': ['Rate', 'Hours', 'Cost'], 'Jun': ['Rate', 'Hours', 'Cost'], 'Jul': ['Rate', 'Hours', 'Cost'] }}
补充说明
- 如果不想依赖
calendar模块,也可以手动定义月份顺序列表:month_order = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],效果完全一致。 - 这种方法支持外层字典包含多个年份的场景,每个年份下的月份都会被单独按时间顺序排序。
内容的提问来源于stack exchange,提问作者Rajagopal Polisetti
相关产品推荐
相关产品推荐

