How about adding a sort parameter to dict methods?

maxm maxm at mxm.dk
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):
        keys=self.data.keys()
        if sort:
            keys.sort()
        return keys

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

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


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

Instead of writing::

keys = theDict.keys():
keys.sort()
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