我想根据具有类似“[0-9]+_[A-Z]+”模式的键对字典进行排序。我希望它按升序排列。
这是我现在的位置:
import operator
myDict = {
'120_str' : 'value',
'150_str' : 'value',
'110_str' : 'value',
'80_str' : 'value',
'10_str' : 'value',
'20_str' : 'value'
}
sortedDict = sorted(myDict.items(), key=operator.itemgetter(0))
我实际拥有的:
sortedDict = {
'10_str' : 'value',
'110_str' : 'value',
'120_str' : 'value',
'150_str' : 'value',
'20_str' : 'value',
'80_str' : 'value'
}
我想要的是:
sortedDict = {
'10_str' : 'value',
'20_str' : 'value',
'80_str' : 'value',
'110_str' : 'value',
'120_str' : 'value',
'150_str' : 'value'
}
请您参考如下方法:
使用_分隔的第一个元素(int)作为排序键:
sorted(myDict.items(), key=lambda x: int(x[0].split('_')[0]))
使用 collections.OrderedDict 来维护顺序:
collections.OrderedDict(sorted(myDict.items(), key=lambda x: int(x[0].split('_')[0])))
示例:
In [109]: sorted(myDict.items(), key=lambda x: int(x[0].split('_')[0]))
Out[109]:
[('10_str', 'value'),
('20_str', 'value'),
('80_str', 'value'),
('110_str', 'value'),
('120_str', 'value'),
('150_str', 'value')]
In [110]: collections.OrderedDict(sorted(myDict.items(), key=lambda x: int(x[0].split('_')[0])))
Out[110]:
OrderedDict([('10_str', 'value'),
('20_str', 'value'),
('80_str', 'value'),
('110_str', 'value'),
('120_str', 'value'),
('150_str', 'value')])
