将字典键从字符串更改为整数

Change dictionary keys from string to integer

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

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}

你从未定义过key

你可以做到

new_b = {int(old_key): val for old_key, val in b.items()}
# int(old_key) will be the key in the new list

由于您正在循环字典 b,您可能想要这样做

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

但这根本没有意义,它改变了 "value",而不是 "key"。

您可能想这样做:

b = {int(key):value for key, value in b.items()}