Sorting a set works, sorting a dictionary fails ?

Larry Hudson orgnut at yahoo.com
Tue Jun 11 05:16:07 EDT 2013


On 06/10/2013 01:29 AM, Νικόλαος Κούρας wrote:
> Trying this:
>
> months = { 'Ιανουάριος':1, 'Φεβρουάριος':2, 'Μάρτιος':3, 'Απρίλιος':4, 'Μάϊος':5, 'Ιούνιος':6, \
> 	   'Ιούλιος':7, 'Αύγουστος':8, 'Σεπτέμβριος':9, 'Οκτώβριος':10, 'Νοέμβριος':11, 'Δεκέμβριος':12 }
>
> for key in sorted( months.values() ):
> 	print('''
> 		<option value="%s"> %s </option>
> 	''' % (months[key], key) )
>
>
> output this:
>
> [Mon Jun 10 11:25:11 2013] [error] [client 79.103.41.173]   File "/home/nikos/public_html/cgi-bin/pelatologio.py", line 310, in <module>, referer: http://superhost.gr/
> [Mon Jun 10 11:25:11 2013] [error] [client 79.103.41.173]     ''' % (months[key], key) ), referer: http://superhost.gr/
> [Mon Jun 10 11:25:11 2013] [error] [client 79.103.41.173] KeyError: 1, referer: http://superhost.gr/
>
> KeyError 1 ??!! All i did was to tell python to sort the dictionary values, which are just integers.
>
Come on now, wake up!!  You do know how to use Python dictionaries don't you?

You can find the dictionary _values_ by using the _key_, but you CAN NOT get the key from the 
value.  (For one thing, keys must be unique but values don't need to be.)  You are trying to use 
the values as keys, but the keys here are all strings, there are NO keys that are integers.  Of 
course this is a dictionary key error.

I think someone already told you this previously, but I'll repeat it, perhaps more verbosely, 
but at least in different words....

The items() function gives you a list of key/value pairs as tuples.  (Not exactly, Python 3 give 
you an iterator not an actual list, but anyway...)
You want to sort this list based on the second element of these tuples (the values).  A simple 
call to the sorted() function will sort based on the first element (the keys).  But you can 
alter this function by using the key parameter, and here you can do it with a short lambda 
function.  (And don't confuse the sorted() key parameter with dictionary keys -- two entirely 
different things that just happen to use the same word.)  See if you can follow this short example:

 >>> d = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5}     #  A short example dictionary
 >>> list(d.items())                       #  Display unsorted list
[('Jan', 1), ('Apr', 4), ('Mar', 3), ('Feb', 2), ('May', 5)]
 >>> sorted(d.items())                     #  Display list sorted by keys (month names)
[('Apr', 4), ('Feb', 2), ('Jan', 1), ('Mar', 3), ('May', 5)]    #  Not what you want
 >>> keys = sorted(d.items(), key=lambda n: n[1])    #  Sort by values (the 2nd element of items)
 >>> for month in keys:                    #  Print this sorted list
	print('Month {} is {}'.format(month[1], month[0]))

Month 1 is Jan
Month 2 is Feb
Month 3 is Mar
Month 4 is Apr
Month 5 is May




More information about the Python-list mailing list