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
alex
  • 2,968
  • 3
  • 23
  • 25
  • Im confused. Why doesn't a numerical sort work to sort the keys? Dictionaries guarantee no sort order for keys so changing the key. – Alan Jun 14 '10 at 20:38
  • 1
    Why not convert them to numbers? ( you can even display them as binary if needed) – mmmmmm Jun 14 '10 at 20:41

3 Answers3

7

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
  • 776,304
  • 153
  • 1,341
  • 1,358
1

You can sort with whatever key you want.

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

0
aDict = dict((('%04d' % oldKey, oldValue) \
             for (oldKey, oldValue) in aDict.iteritems()))

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

Tamás
  • 47,239
  • 12
  • 105
  • 124