OrderedDict对大键的有缺陷的顺序

时间:2017-06-09 21:21:51

标签: python sorting dictionary python-3.5

hybrid_dict = OrderedDict(sorted(hybrid_dict.items(), key=lambda t: t[0]))
for k,v in hybrid_dict.items():
    print(k)

输出:

9148000.0
9149000.0
915000.0
9150000.0
9151000.0 
9152000.0 

915000.0不应该在那里。

为什么命令dict像这样命令我的字典? print(hybrid_dict)给出相同的顺序。

1 个答案:

答案 0 :(得分:0)

我检查了一下,我认为这是因为你的密钥是字符串而不是数字和字符串比较Lexicographical order

要将它们排序为数字,只需修改key - 函数:

from collections import OrderedDict
hybrid_dict = dict.fromkeys(['9148000.0','9149000.0','915000.0','9150000.0','9151000.0','9152000.0'])
hybrid_dict = OrderedDict(sorted(hybrid_dict.items(), key=lambda t: float(t[0])))
for k,v in hybrid_dict.items():
    print(k)

给出:

915000.0
9148000.0
9149000.0
9150000.0
9151000.0
9152000.0