Rename keys in a dictionary

I want to rename the dictionary keys, which are ints, and I need them to be ints with leading zeros 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 i am doing now but i know there is a better way

tmpDict = {}
  for oldKey in aDict:
 tmpDict['%04d'%int(oldKey)] = aDict[oldKey]
newDict = tmpDict
+3
source share
3 answers

You are going this wrong way. If you want to output records from a dict in sorted form, you need to sort it on extraction.

for k in sorted(D, key=int):
  print '%s: %r' % (k, D[k])
+7
source

You can sort any key you want.

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

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

... %03d, , .

0

Source: https://habr.com/ru/post/1750008/


All Articles