当键是由字符串表示的分数时,如何按值对dict进行排序?

时间:2012-09-27 22:30:40

标签: python dictionary

我需要对dict进行排序,其中键是由字符串表示的分数,需要按其数值排序:

即:

exp_time = {"2":10, "1/2":5:, "2.5":11, "1/200":9, "15":3, "1/30":6}

结果应该是这样的(降序):

15
2.5
2
1/2
1/30
1/200

1 个答案:

答案 0 :(得分:12)

>>> import fractions
>>> exp_time = {"2":10, "1/2":5, "2.5":11, "1/200":9, "15":3, "1/30":6}
>>> sorted(exp_time, key=fractions.Fraction, reverse=True)
['15', '2.5', '2', '1/2', '1/30', '1/200']