How about adding a sort parameter to dict methods?
maxm at mxm.dk
Wed Dec 19 00:35:26 CET 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
def __init__(self, dict=None):
def keys(self, sort=0):
def values(self, sort=0):
def items(self, sort=None):
return [(key, self.data[key]) for key in self.keys(sort=1)]
values = [(self.data[key],
(key, self.data[key])) for key in self.data.keys()]
return [item 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