Skip to content Skip to sidebar Skip to footer

How To Properly Sort Items In A Python Dictionary?

I have created a dictionary in python to deal handle the change for a purchase. money = { '$100.00' : 0, '$50.00' : 0, '$20.00' : 0,'$10.00' : 0, '$5.00' : 0, '$1.00

Solution 1:

The sorting is happening lexicographically, i.e. alphabetically, one character at a time. Change your sort function to remove the dollar sign and convert to float:

keyList.sort(key=lambda x:float(x[1:]))

Or better yet, remove the "$" from the key, leaving the key a float, and only add the "$" when printing

Solution 2:

This is happening because you are sorting strings, which are sorted lexicographically (order in which it would show up if it was in an English dictionary).

What you want is to sort them by their floatified values, which can be done like this:

>>>money = { '$100.00' : 0, '$50.00' :  0, '$20.00' : 0,'$10.00' : 0,...'$5.00' : 0, '$1.00' : 0,'$0.25' : 0, '$0.10' : 0, '$0.05' : 0,...'$0.01' : 0}>>>for val insorted(money, key=lambda s: float(s.lstrip("$"))):...print(val, money[val])... 
$0.01 0
$0.05 0
$0.10 0
$0.25 0
$1.00 0
$5.00 0
$10.00 0
$20.00 0
$50.00 0
$100.00 0

Solution 3:

Since you're storing Strings, its sorting them by their String value. You'll need to convert them to something like Decimals (which is advised for dealing with money), and then you will be able to sort them.

#Hint:

fromdecimal import Decimal

dollarString ='$100.00'

dollarDecimal =Decimal(dollarString.strip('$'))

Solution 4:

If you don't mind third party libraries, check out natsort. It is designed for situations exactly like this

import natsort
money = { '$100.00' : 0, '$50.00' :  0, '$20.00' : 0,'$10.00' : 0,
          '$5.00' : 0, '$1.00' : 0,'$0.25' : 0, '$0.10' : 0, '$0.05' : 0,
          '$0.01' : 0}
keylist = natsort.natsorted(money)
print(keylist)
# prints ['$0.01', '$0.05', '$0.10', '$0.25', '$1.00', '$5.00', '$10.00', '$20.00', '$50.00', '$100.00']

Or, if you want the in-place sort:

keylist = list(money)
keylist.sort(key=natsort.natsort_key)
print(keylist)
# prints ['$0.01', '$0.05', '$0.10', '$0.25', '$1.00', '$5.00', '$10.00', '$20.00', '$50.00', '$100.00']

Natsort automatically handles numbers inside strings so you get a natural sort order, not lexicographical order.

Post a Comment for "How To Properly Sort Items In A Python Dictionary?"