Python中的字典是无序的。您可以将所需的结果作为
list
>>> d = {'10': -10, 'ZT21': 14, 'WX21': 12, '2': 15, '5': -3, 'UM': -25}>>> keyorder = ['ZT21', '10', 'WX21', 'UM', '5', '2']>>> sorted(d.items(), key=lambda i:keyorder.index(i[0]))[('ZT21', 14), ('10', -10), ('WX21', 12), ('UM', -25), ('5', -3), ('2', 15)]
或作为OrderedDict
>>> from collections import OrderedDict>>> OrderedDict(sorted(d.items(), key=lambda i:keyorder.index(i[0])))OrderedDict([('ZT21', 14), ('10', -10), ('WX21', 12), ('UM', -25), ('5', -3), ('2', 15)])
如果您要执行许多 *** 作,则将a
dict用作键阶会更有效
>>> keyorder = {k:v for v,k in enumerate(['ZT21', '10', 'WX21', 'UM', '5', '2'])}>>> OrderedDict(sorted(d.items(), key=lambda i:keyorder.get(i[0])))OrderedDict([('ZT21', 14), ('10', -10), ('WX21', 12), ('UM', -25), ('5', -3), ('2', 15)])
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)