How about adding a sort parameter to dict methods?

maxm maxm at
Tue Dec 18 18:35:26 EST 2001

I have just spend some time writing code to make a dictionary produce sorted
output when using the keys, values, and items methods.

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.

Well .. this code shows what I mean::

from UserDict import UserDict

class OrderedDict(UserDict):

    def __init__(self, dict=None):
        UserDict.__init__(self, dict)

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

    def values(self, sort=0):
        if sort:
        return values

    def items(self, sort=None):
        if sort=='keys':
            return [(key,[key]) for key in self.keys(sort=1)]
        elif sort=='values':
            values = [([key],
                       (key,[key])) for key in]
            return [item[1] for item in values]

Wouldn't that be nice to have as a standard in the language? I think so.

Instead of writing::

keys = theDict.keys():
for key in keys():
    value = theDict[key]
    print key, value

it would be possible to just write::

for key, val in theDict.items(sort='keys')
    print key, val

The problem off course is all the people having rolled their own version if
dicts with parameters in the keys(), values(), items() methods.

Alternatively it could be possible to pass a sort-function as a parameter,
then it would be really flexible, but a bit more comlicated.

regards Max M

More information about the Python-list mailing list