Sorting a set works, sorting a dictionary fails ?
Denis McMahon
denismfmcmahon at gmail.com
Mon Jun 10 22:14:47 EDT 2013
On Mon, 10 Jun 2013 03:42:38 -0700, Νικόλαος Κούρας wrote:
> for key in sorted( months.values() ):
> print('''
> <option value="%s"> %s </option>
> ''' % (months[key], key) )
> ==============
>
> please tell me Uli why this dont work as expected to.
Because inside the for loop, your value 'key' is an item from the sorted
list of the values part of months. When you use months[key], you're
trying to look up in months based on the value part, not the key part.
Calling it key is confusing you.
Try this:
things = { "a":1, "b":3, "c":2 }
for thing in sorted( things.values() ):
print thing
>> Prints 1, 2, 3
for thing in sorted( things.keys() ):
print thing
>> Prints a, b, c
Now although things["b"] is a valid reference because "b" is a key in a
key - value pair, things[3] is not a valid reference, because 3 is not a
key in a key - value pair.
--
Denis McMahon, denismfmcmahon at gmail.com
More information about the Python-list
mailing list