alex
alex

Reputation: 3118

rename keys in a dictionary

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

Upvotes: 3

Views: 2910

Answers (3)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

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])

Upvotes: 7

user97370
user97370

Reputation:

You can sort with whatever key you want.

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

Upvotes: 1

Tamás
Tamás

Reputation: 48041

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

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

Upvotes: 0

Related Questions