重命名字典中的键 [英] rename keys in a dictionary
本文介绍了重命名字典中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如我的密钥如下:
'1' '101','11'
我需要他们:
'001','101','011'
这是我现在在做什么,但我知道有一个更好的方法
tmpDict = {}
pre>
在aDict中的oldKey:
tmpDict ['%04d'%int(oldKey)] = aDict [oldKey]
newDict = tmpDict
解决方案你会做错误的方式。如果你想以一种排序的方式从dict中输入条目,那么你需要对提取进行排序。
(D,key = int):
print'%s:%r'%(k,D [k])
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
解决方案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])
这篇关于重命名字典中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文