How to properly sort items in a Python dictionary? -
i have created dictionary in python deal handle change purchase.
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}
however when want print this, can't seem able "least greatest" piece of currency.
this have done in attempt sort it:
keylist = list(money.keys()) keylist.sort() key in keylist: print(key, money[key])
however result given goes ...$1 -> $10 -> $100 -> $20...any suggestions $1 -> $5 -> $10...?
the sorting happening lexicographically, i.e. alphabetically, 1 character @ time. change sort function remove dollar sign , convert float:
keylist.sort(key=lambda x:float(x[1:]))
or better yet, remove "$"
key, leaving key float, , add "$"
when printing
Comments
Post a Comment