如何正确排序Python字典中的项目? [英] How to properly sort items in a Python dictionary?
问题描述
我已经在python中创建了一个字典来处理购买的更改.
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' : 0,'$0.25' : 0, '$0.10' : 0, '$0.05' : 0,
'$0.01' : 0}
但是,当我要打印此货币时,我似乎无法从最小到最大"的货币进行打印.
However when I want to print this, I can't seem to be able to do this from "least to greatest" piece of currency.
这是我尝试对它进行排序的步骤:
This is what I have done in an attempt to sort it:
keyList = list(money.keys())
keyList.sort()
for key in keyList:
print(key, money[key])
但是给出的结果从... $ 1-> $ 10-> $ 100-> $ 20 ...有任何建议,它将是$ 1-> $ 5-> $ 10 ...?
However the result given goes from ...$1 -> $10 -> $100 -> $20...Any suggestions so it will be $1 -> $5 -> $10...?
推荐答案
之所以会这样,是因为您正在对字符串进行排序,这些字符串按字典顺序排序(如果在英语词典中,则显示顺序).
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 in sorted(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
这篇关于如何正确排序Python字典中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!