a question regarding conciseness

Max M maxm at mxm.dk
Fri Feb 22 05:05:57 EST 2002


Rajarshi Guha wrote:

> Why can't I use d.keys().sort() directly? And is there any other more 
> concise (elegent?) way to loop over sorted dictionary keys?

You could just create your own dict that returns sorted keys:

regards Max M

#################################################

import UserDict

class sDict(UserDict.UserDict):

     def keys(self):
         keys = self.data.keys()
         keys.sort()
         return keys

     def values(self):
         return [self.data[key] for key in self.keys()]

     def items(self):
         return [(key, self.data[key]) for key in self.keys()]


sDict = sDict()
sDict[1] = 10
sDict[2] = 20
sDict[3] = 30
sDict[4] = 40
sDict[5] = 50

print sDict
for key in sDict.keys():
     print sDict[key]

for key, val in sDict.items():
     print '%s: %s' % (key, val)

-----------------------------

{5: 50, 4: 40, 3: 30, 2: 20, 1: 10}

10
20
30
40
50

1: 10
2: 20
3: 30
4: 40
5: 50




More information about the Python-list mailing list