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

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -