Reputation: 4122
I am trying to convert the keys of a dictionary from being strings into integers using this code:
b = {"1":0,"2":0,"3":0,"4":0,"5":0}
for newkey in b:
newkey[key] = int(newkey[key])
print b
However this keeps producing the following error:
Traceback (most recent call last):
File "C:\Python27\counter2", line 22, in <module>
newkey[key] = int(newkey[key])
NameError: name 'key' is not defined
I want the final output to look like this:
b = {1:0,2:0,3:0,4:0,5:0}
Can anyone tell me what I am doing wrong?
Thanks
Upvotes: 4
Views: 9501
Reputation: 239443
In this code
for newkey in b:
newkey[key] = int(newkey[key])
key
has never been defined before. Perhaps you meant newkey
? Instead, simply reconstruct the dictionary with dictionary comprehension, like this
>>> 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}
Or you can use dict.iteritems()
, like this
>>> {int(key): value for key, value in b.iteritems()}
{1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
Upvotes: 9
Reputation: 34146
Since you are looping the dictionary b
, you may want to do
for newkey in b:
b[newkey] = int(b[newkey])
print b
But this doesn't make sense at all, it changes the "value", not the "key".
You may want to do this instead:
b = {int(key):value for key, value in b.items()}
Upvotes: 0
Reputation: 11691
You never defined key
You can do
new_b = {int(old_key): val for old_key, val in b.items()}
# int(old_key) will be the key in the new list
Upvotes: 1