[Python-Dev] PEP 265 - Sorting dicts by value

David Harrison dave.l.harrison at gmail.com
Mon Sep 13 06:44:25 CEST 2004


> > In the sense that items() can still be used as before, it remains
> > consistent.  However since the same argument could be used to equally
> > promote the modification of other  dict functions to accept such
> > arguments - such as keys(values_first=0)  - to make the change to
> > items() alone is (in my humble opinion) inconsistent.
> > But that's just my opinion, others may feel differently.
>
> To me, neither mydict.keys(values_first=whatever) nor
> mydict.values(values_first=whatever) make any sense: these methods
> return a list of only keys or only values, so saying "values first"
> when you're getting a list of keys is meaningless.

Oops my mistake, I was thinking along the lines of requesting a sort
order based on value (i.e. keys() returns in the order of its values,
increasing or decreasing).

So my misunderstanding aside ;-) ...

We would have the following situation (just to clarify) :

>>> d = { 'a' : 1 , 'b' :2, 'c':0 }
>>> itemList = d.items(values_first=1)
>>> itemList
[(1, 'a'), (2, 'b'), (0, 'c')]
>>> itemList.sort()
>>> itemList
[(0, 'c'), (1, 'a'), (2, 'b')]

That is probably my preferred option for this usage.

But to play devil's advocate for a minute.  Considering that a dict is
a key based
data structure and not a sequential structure, does it really make sense to be
able to request its inversion ?

For example :
>>> d = { 'a' : [1,2,3] , 'b' : [4,5,6], 'c':[7,8,9] }
>>> d.items(values_first=1)
[ ([1,2,3], 'a'), ([4,5,6], 'b'), ([7,8,9], 'c') ]

This just doesnt make sense, nor would it make sense if the values were objects.

The only use case raised was for counting instances of an item in a
dict, and then inverting _that_ dict (ie. the one that stored the
count values) .

e.g.

for key in d.keys():
        d[key] = d.get(key, 0) + 1

items = [(v,k) for k,v in d.items()]
items.sort()
items.reverse()
items = [(k,v) for v,k in items]

So I'll also raise again my question of whether it is reasonable to
implement a functionality that is not going to be used as a part of
the primary purpose of a dict.  This functionality extension is just
an implementation of one way of using a dict - not necessarily an
example of 'missing functionality' to me.


More information about the Python-Dev mailing list