简体   繁体   English

如何对具有月份名称作为键的 python 字典进行排序

[英]how to sort a python dictionary having month names as keys

I have a python dictionary like我有一个 python 字典,比如

{'JUL':15,'MAR': 54,'DEC':65,'OCT':90}

I want it to be sorted according to months say, MAR, JUL, OCT and DEC in python.我希望它按照月份排序,比如 python 中的 MAR、JUL、OCT 和 DEC。

How can I do it?我该怎么做?

Dictionaries are orderless, you cannot sort a dictionary. 字典是无序的,你不能对字典进行排序。 You would need an ordereddict, which you can create from a list of sorted tuples of key,value pairs of your current dict. 您需要一个ordereddict,您可以从当前dict的键,值对的已排序元组列表中创建。

>>> months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
>>> input = {'JUL':15,'MAR': 54,'DEC':65,'OCT':90}
>>> from collections import OrderedDict
>>> OrderedDict(sorted(input.items(),key =lambda x:months.index(x[0])))
OrderedDict([('MAR', 54), ('JUL', 15), ('OCT', 90), ('DEC', 65)])

You want to sort them by the number of the month so you need to create a Mapping from your month abbreviations to the number of that month: 您希望按月份数对它们进行排序,因此您需要创建从月份缩写到该月份数的映射:

dic = {'JUL':15, 'MAR': 54,'DEC':65,'OCT':90}

import calendar
month_numeric_mapping = {abb: index for abb in dic 
                                    for index, long in enumerate(calendar.month_name[1:]) 
                                    if str.lower(abb) in str.lower(long)}

>>> month_numeric_mapping
{'DEC': 11, 'JUL': 6, 'MAR': 2, 'OCT': 9}

Then you define a function that can be used with sorted to get that number: 然后定义一个可以与sorted一起使用的函数来获取该数字:

def getMonthNumber(item):
    return month_numeric_mapping[item[0]]

and finally you need to have a order-aware dictionary OrderedDict to store the sorted output: 最后你需要一个订单感知字典OrderedDict来存储已排序的输出:

>>> from collections import OrderedDict
>>> a = OrderedDict(sorted(dic.items(), key=getMonthNumber))
>>> a
OrderedDict([('MAR', 54), ('JUL', 15), ('OCT', 90), ('DEC', 65)])


Another possibility is to use calendar.month_abbr : 另一种可能性是使用calendar.month_abbr

 month_numeric_mapping = {abbr.upper(): i for i, abbr in enumerate(calendar.month_abbr[1:])} def getMonthNumber(item): return month_numeric_mapping[item[0]] a = OrderedDict(sorted(dic.items(), key=getMonthNumber)) >>> a OrderedDict([('MAR', 54), ('JUL', 15), ('OCT', 90), ('DEC', 65)]) 

A key sort function like the PHP ksort() : 一个关键的排序函数,如PHP ksort()

def ksort(d, func = None):
    keys = d.keys()
    keys.sort(func)
    return keys

for k in ksort(dic):
    print k, d[k]

You can use Ordered Dictionaries in Python using collections module. 您可以使用集合模块在Python中使用Ordered Dictionaries。 See the below example. 请参阅以下示例。

import collections

print 'Regular dictionary:'
d = {}
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'

for k, v in d.items():
    print k, v

print '\nOrderedDict:'
d = collections.OrderedDict()
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'

for k, v in d.items():
    print k, v

Output 产量

Regular dictionary:
a A
c C
b B
e E
d D

OrderedDict:
a A
b B
c C
d D
e E

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

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