按键的前四个字符排序Python字典
我有一个Python字典,长得像这样:
{'666 -> 999': 4388, '4000 -> 4332': 4383, '1333 -> 1665': 7998, '5666 -> 5999': 4495, '3666 -> 3999': 6267, '3000 -> 3332': 9753, '6333 -> 6665': 7966, '0 -> 332': 877}
字典里的键(也就是名字)都是字符串,每个键表示一个数字范围。我想根据每个键里的第一个数字来给这个字典排序。直接用sorted函数对字典排序不行,因为字符串“666”在字典序上比字符串“1000”要大。感谢大家的建议!
1 个回答
10
使用排序关键字:
sorted(yourdict, key=lambda k: int(k.split()[0]))
这段代码会返回一个列表,列表里的关键字会根据关键字的第一部分进行数字排序(通过空格分开)。
示例:
>>> yourdict = {'666 -> 999': 4388, '4000 -> 4332': 4383, '1333 -> 1665': 7998, '5666 -> 5999': 4495, '3666 -> 3999': 6267, '3000 -> 3332': 9753, '6333 -> 6665': 7966, '0 -> 332': 877}
>>> sorted(yourdict, key=lambda k: int(k.split()[0]))
['0 -> 332', '666 -> 999', '1333 -> 1665', '3000 -> 3332', '3666 -> 3999', '4000 -> 4332', '5666 -> 5999', '6333 -> 6665']
同时对关键字和对应的值进行排序:
sorted(yourdict.items(), key=lambda item: int(item[0].split()[0]))
这样会生成关键字和对应值的配对:
>>> sorted(yourdict.items(), key=lambda item: int(item[0].split()[0]))
[('0 -> 332', 877), ('666 -> 999', 4388), ('1333 -> 1665', 7998), ('3000 -> 3332', 9753), ('3666 -> 3999', 6267), ('4000 -> 4332', 4383), ('5666 -> 5999', 4495), ('6333 -> 6665', 7966)]
你可以用这个生成一个collections.OrderedDict()
对象:
>>> from collections import OrderedDict
>>> OrderedDict(sorted(yourdict.items(), key=lambda item: int(item[0].split()[0])))
OrderedDict([('0 -> 332', 877), ('666 -> 999', 4388), ('1333 -> 1665', 7998), ('3000 -> 3332', 9753), ('3666 -> 3999', 6267), ('4000 -> 4332', 4383), ('5666 -> 5999', 4495), ('6333 -> 6665', 7966)])