[Tutor] Sorting a dictionary by a value when the values are tuples
Steven D'Aprano
steve at pearwood.info
Sat Mar 5 11:11:11 CET 2011
ranjan das wrote:
> This is a small example i created
>
>
> from operator import itemgetter
> temp={'4':(2,3), '2':(5,8)}
> print temp.items()
> new_temp=sorted(temp.items(), key=itemgetter(1)
> print new_temp
Another syntax error. Please ensure that you test your code before
posting. In this case, it's easy to fix: you're missing a closing
bracket in the call to sorted().
> I want to sort the dictionary by the value in the first element of the tuple
> ((2,3) and (5,8)) and then the second value.
That would be the ordinary sort order of tuples.
> How do i do it? by setting key=itemgetter(1), it seems to sort the dict by
> the first value of the tuple. But I am not able to do it for the second
> value.
You can't sort *dicts*, because they are unordered. However, you extract
the key:value items from the dict into a list, which gives you a list of
tuples:
>>> from operator import itemgetter
>>> temp={'4':(2,3), '2':(5,8)}
>>> print temp.items()
[('2', (5, 8)), ('4', (2, 3))]
You want to ignore the key part (the first item in the *outer* tuples,
namely '2' and '4'), and just sort by the value part (the second item of
the outer tuples, namely (2, 3) and (5, 8) -- note that these are
themselves also tuples.
The way to sort them is using itemgetter(1), exactly as you tried:
>>> new_temp=sorted(temp.items(), key=itemgetter(1))
>>> print new_temp
[('4', (2, 3)), ('2', (5, 8))]
What makes you think that it did not work correctly? Here is a better
example, showing that it works fine:
>>> temp = {'a':(2,3), 'b':(5,8), 'c':(5,1), 'd':(2,1)}
>>> temp.items()
[('a', (2, 3)), ('c', (5, 1)), ('b', (5, 8)), ('d', (2, 1))]
>>> sorted(temp.items(), key=itemgetter(1))
[('d', (2, 1)), ('a', (2, 3)), ('c', (5, 1)), ('b', (5, 8))]
--
Steven
More information about the Tutor
mailing list