Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change dictionary keys from string to integer

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

like image 683
gdogg371 Avatar asked Sep 04 '25 01:09

gdogg371


2 Answers

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}
like image 178
thefourtheye Avatar answered Sep 07 '25 17:09

thefourtheye


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
like image 43
sedavidw Avatar answered Sep 07 '25 16:09

sedavidw