[Tutor] Floats as dictionary keys

alan.gauld@bt.com alan.gauld@bt.com
Tue Apr 1 12:52:12 2003


> def getSortedKeys(dictionary):
>      keys = dictionary.keys()
>      keys.sort()
>      return keys
> ...
> for dice in range(5)[1:]:
>          average = findAverage(dice, sides)
>          diceString = "%dd%2d" % (dice, sides)
>          diceFirst[diceString] = average

So you make a string and use it as the key. 
The same key that getSortedKeys() uses to sort.

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

And here you print out the value converted to a string.

> 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:

But you aren't sorting by value you are sorting by keys which 
you explicitly force to be strings. I don't understand.

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

It doesn't appear to be stringizing them, you do that when you 
print them.

I think I'm missing something?

Alan g.