Velocity Reviews > Sorting a set works, sorting a dictionary fails ?

# Sorting a set works, sorting a dictionary fails ?

Νικόλαος Κούρας
Guest
Posts: n/a

 06-10-2013
months = { '@@@@@@@@@@':0, 'Ιανουάριος':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) )
==============

please tell me Uli why this dont work as expected to.

Steven D'Aprano
Guest
Posts: n/a

 06-10-2013
On Mon, 10 Jun 2013 03:42:38 -0700, ΞΞΉΞΊΟΞ»Ξ±ΞΏΟ ΞΞΏΟΟΞ±Ο wrote:

> for key in sorted( months.values() ):

> please tell me Uli why this dont work as expected to.

Because values are not keys. You are looking at the values, and trying to
use them as keys.

months = {'Ξ¦Ξ΅Ξ²ΟΞΏΟΞ¬ΟΞΉΞΏΟ':2, 'ΞΞ±Ξ½ΞΏΟΞ¬ΟΞΉΞΏΟ':1}
print("==Values==")
for x in sorted(months.values()):
print(x)

print("==Keys==")
for x in sorted(months.keys()):
print(x)

prints:

==Values==
1
2
==Keys==
ΞΞ±Ξ½ΞΏΟΞ¬ΟΞΉΞΏΟ
Ξ¦Ξ΅Ξ²ΟΞΏΟΞ¬ΟΞΉΞΏΟ

--
Steven

Ulrich Eckhardt
Guest
Posts: n/a

 06-10-2013
Am 10.06.2013 11:48, schrieb ΞΞΉΞΊΟΞ»Ξ±ΞΏΟ ΞΞΏΟΟΞ±Ο:
> After many tried this did the job:
>
> for key in sorted(months.items(),key=lambda num : num[1]):
> print('''
> <option value="%s"> %s </option>
> ''' % (key[1], key[0]) )

This code is still sending a misleading message. What you are referring
to as "key" here is in fact a (key, value) tuple. I'd use FΓ‘bio's
suggestion and use the automatic splitting:

for name, idx in sorted(months.items(), key=lambda num : num[1]):
print('month #{} is {}'.format(idx, name))

> but its really frustrating not being able to:
>
> for key in sorted( months.values() ):
> print('''
> <option value="%s"> %s </option>
> ''' % (months[key], key) )
>
> Which seemed to be an abivous way to do it.

You are composing three things:

1. months.values() - gives you a sequence with the month numbers
2. sorted() - gives you a sorted sequence
3. for-iteration - iterates over a sequence

At which point is Python doing anything non-obvious? Also, have you
considered reversing the dictionary mapping or creating a second one
with the reversed mapping? Or maybe take a look at collections.OrderedDict?

> names set() was able to order like this why not the dictionary too?

Well, why don't you use a set then, if it solves your problem? An in
which place does anything behave differently? Sorry to bring you the

Uli