Newboy11
Newboy11

Reputation: 3136

sort dictionary with float values in python

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?

Upvotes: 4

Views: 8131

Answers (3)

Artem Yanovskiy
Artem Yanovskiy

Reputation: 1

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()

Upvotes: 0

Suyog Rajbhandari
Suyog Rajbhandari

Reputation: 63

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)]

Upvotes: 3

jfowkes
jfowkes

Reputation: 1565

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.

Upvotes: 0

Related Questions