[Tutor] Floats as dictionary keys

Brian Christopher Robinson brian@dungeoncrawl.org
Tue Apr 1 11:02:01 2003


I've got this code:

def getSortedKeys(dictionary):
     keys = dictionary.keys()
     keys.sort()
     return keys


def findAverage(dice, sides):
         # returns a float, details not important

diceFirst = {}
averagesFirst = {}
for dice in range(5)[1:]:
     for sides in [4, 6, 8, 10, 12]:
         average = findAverage(dice, sides)
         diceString = "%dd%2d" % (dice, sides)
         diceFirst[diceString] = average
         averagesFirst[average] = diceString

for key in getSortedKeys(diceFirst):
     print key + ": " + str(diceFirst[key])

for key in getSortedKeys(averagesFirst):
     print str(averagesFirst[key]) + ": " + key

The problem I have is that the floats get turned into strings and get 
sorted wrong.  The output I get for the second loop looks like this:

4d10: 10.7147
3d12: 11.1702
4d12: 12.2725
1d 4: 3.3886
1d 6: 4.2657
2d 4: 4.6639
1d 8: 5.0885
3d 4: 5.6046
2d 6: 5.783
1d10: 6.1249
4d 4: 6.2817
3d 6: 6.8376
2d 8: 7.0938
1d12: 7.1222
4d 6: 7.6049
3d 8: 8.2827
2d10: 8.3605
4d 8: 9.1556
3d10: 9.6382
2d12: 9.745

Is there any way to force the dictionary not to stringize my float values?


-- 
"Words are poison." - Nick on love