How about adding a sort parameter to dict methods?

Andrew Dalke dalke at dalkescientific.com
Tue Dec 18 23:45:32 EST 2001


maxm wrote:
> My guess is that a LOT of people has done this before me.
> So I just wondered if it wouldn't be a good idea to add
> a 'sort' parameter to the method to specify if it should
> be sorted or not.

>    def keys(self, sort=0):
>        keys=self.data.keys()
>        if sort:
>            keys.sort()
>        return keys

If it were done, it would need to take a sort function (as
you mentioned later in your post).  Flags are often the
ugly solution, and your approach of passing in a string
value as the flag is almost never the right solution.
Here's what it looks like with a sort function:

class _no_sort:
  pass

class OrderedDict(UserDict.UserDict):
  ...
  def keys(self, sort = _no_sort):
    keys = self.data.keys()
    if sort is not _no_sort:
        keys.sort(sort)
    return keys

(The '_no_sort' class is needed to distinguish between
using None, for the default sorting method, as compared to
no specified argument, meaning do not apply a sort.  This
could also be done with *args as in

  def keys(self, *sort):
    if sort and len(sort) > 1:
        raise TypeError("too many parameters")
    keys = self.data.keys()
    if sort:
        keys.sort(sort[0])
    return keys
)


What you want is needed less often than you think.  Other
solutions are possible, like:

def sorted_list(list, fctn = None):
    list.sort(fctn)
    return list

result = sorted_list(d.keys())

There's also a problem in what you have.  People expect
that

  dict.items() == zip(dict.keys(), dict.values())

and that's a guarantee made in the documentation.  But
once you pass in a sort function that doesn't occur.  It,
some may want the sort function for 'values' to return
the list sorted by the keys, even though the keys aren't
returnd.

In addition, roughly as often people want the elements in
insertion order, not in sort order.

Since there are many equally "valid" modifications to
dictionaries and their methods, the Pythonic solution is to
punt - provide the base functionality that other people can
tweak for their specific needs.  And that functionality
should be simple.

What's present isn't going to aquire your proposed changes,
or anything like it.  What you did is the Pythonic solution.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list