重命名字典中的键 [英] rename keys in a dictionary

查看:145
本文介绍了重命名字典中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重命名字典的键是哪些是int,我需要它们是前导零的int,以便它们排序正确。



例如我的密钥如下:

 '1' '101','11'

我需要他们:

 '001','101','011'

这是我现在在做什么,但我知道有一个更好的方法

  tmpDict = {} 
在aDict中的oldKey:
tmpDict ['%04d'%int(oldKey)] = aDict [oldKey]
newDict = tmpDict
pre>

解决方案

你会做错误的方式。如果你想以一种排序的方式从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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆