2

I need to sort a dict, where keys are fractions represented by strings and need to be sorted by its numerical values:

i.e.:

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

result should be like this(descending order):

15
2.5
2
1/2
1/30
1/200
mawueth
  • 2,668
  • 1
  • 14
  • 12
zalkap
  • 101
  • 1
  • 5

1 Answers1

13
>>> 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']
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • 2
    +1, I didn't know about the `fractions` module. I was about to post the same answer but with a hand-rolled implementation of `fractions.Fraction`. – Adam Rosenfield Sep 27 '12 at 22:35
  • 1
    It's worth mentioning though that a standard dictionary is **unordered**. If all the OP cares about is this final list that's fine, otherwise one should use an ordered dict like `collections.OrderedDict` (Python 2.7+). – Lukas Graf Sep 27 '12 at 22:39