我正在尝试使用以下代码将字典的键从字符串转换为整数:

b = {"1":0,"2":0,"3":0,"4":0,"5":0}

for newkey in b:
        newkey[key] = int(newkey[key])
print b

但是,这会不断产生以下错误:
Traceback (most recent call last):
  File "C:\Python27\counter2", line 22, in <module>
    newkey[key] = int(newkey[key])
NameError: name 'key' is not defined

我希望最终输出如下所示:
b = {1:0,2:0,3:0,4:0,5:0}

谁能告诉我我做错了什么?

谢谢

最佳答案

在这段代码中

for newkey in b:
        newkey[key] = int(newkey[key])
key 以前从未定义过。也许你的意思是 newkey ?相反,只需用字典理解重建字典,就像这样
>>> b = {"1": 0, "2": 0, "3": 0, "4": 0, "5": 0}
>>> {int(key):b[key] for key in b}
{1: 0, 2: 0, 3: 0, 4: 0, 5: 0}

或者你可以使用 dict.iteritems() ,像这样
>>> {int(key): value for key, value in b.iteritems()}
{1: 0, 2: 0, 3: 0, 4: 0, 5: 0}

关于python - 将字典键从字符串更改为整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27910621/

10-12 21:20