4

I'm sorting dictionary with float values to ascending order. Here's my code

dicdata = {'mike': 15.12, 'jenny': 2.53, 'glenn' : 5.16, 'Meo': 1.01}

sorted_dicdata = sorted(dicdata.items(), key=operator.itemgetter(1), reverse=True)

The output is not accurate. it gives me glenn:5.16 mike:15.12 jenny:2.53 meo:1.01 How can i fix this?

6
  • Just to note: they're float values - not to be confused with decimal.Decimal values Commented Oct 21, 2015 at 15:33
  • Why do you think it isn't accurate? Commented Oct 21, 2015 at 15:33
  • 3
    Also - from your stated output glenn:5.16 mike:15.12 jenny:2.53 meo:1.01 - that looks very much like you've copy and pasted an attempt at converting it back to a dict - rather than a list of 2-tuples which sorted which return in this case. Can't help but feel you haven't posted your full code here... Commented Oct 21, 2015 at 15:35
  • Does sorting dictionary with float values are unreliable? Commented Oct 21, 2015 at 15:37
  • @Newboy11 dictionaries, by default, are unsorted. It has nothing to do with the float values Commented Oct 21, 2015 at 15:39

3 Answers 3

3

The following code works if you want from decimal to the ascending order

    >>> import operator
    >>> print sorted(dicdata.items(), key=operator.itemgetter(1))
    [('Meo', 1.01), ('jenny', 2.53), ('glenn', 5.16), ('mike', 15.12)]
Sign up to request clarification or add additional context in comments.

1 Comment

Works pretty well and fast in python3 - Thanks!
0

The following correctly sorts the dictionary (Python 2.7.9 and Python 3.4.2)

>>> import operator
>>> dicdata={'mike':15.12, 'jenny':2.53, 'glenn': 5.16, 'Meo': 1.01}
>>> sorted_dicdata = sorted(dicdata.items(), key=operator.itemgetter(1),        reverse=True)
>>> sorted_dicdata
[('mike', 15.12), ('glenn', 5.16), ('jenny', 2.53), ('Meo', 1.01)]

I put quotes around the dictionary keys since I assume they are meant to be strings.

Comments

0

Way I found - convert dict to pandas series, sort, and convert back.

import pandas as pd

series = pd.Series(dictionary)
series.sort_values(axis=0, ascending=False, inplace=True, kind='quicksort', na_position='last', ignore_index=False, key=None)
series.to_dict()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.