views:

94

answers:

3

i want to rename the keys of a dictionary are which are ints, and i need them to be ints with leading zeros's so that they sort correctly.

for example my keys are like:

'1','101','11'

and i need them to be:

'001','101','011'

this is what im doing now, but i know there is a better way

tmpDict = {}
  for oldKey in aDict:
 tmpDict['%04d'%int(oldKey)] = aDict[oldKey]
newDict = tmpDict
A: 
aDict = dict((('%04d' % oldKey, oldValue) \
             for (oldKey, oldValue) in aDict.iteritems()))

...or %03d if you need three digits as in your example.

Tamás
+1  A: 

You can sort with whatever key you want.

So, for example: sorted(mydict, key=int)

Paul Hankin
+7  A: 

You're going about it the wrong way. If you want to pull the entries from the dict in a sorted manner then you need to sort upon extraction.

for k in sorted(D, key=int):
  print '%s: %r' % (k, D[k])
Ignacio Vazquez-Abrams