How to convert value in dictionary from string to int

Viewed 656

I have a list of dictionaries, where both the key and value are strings. I am importing the data from a CSV file. The dictionaries look like this:

{'1A': '1',
 '1B': '1',
 '1C': '2'}

I would like to change the values into integers.

I have looked around for a solution but I don't seem to find anything that works.

This is my code (the list is called 'buyers'):

for i in buyers:
    for k, v in i.items():
        i[v] = int(i[v])

I receive this error:

i[v] = int(i[v])

KeyError: '1'

I'm not sure what to do because it says my error is the '1', which seems to me like it should be able to be converted into an int.

2 Answers

You can use list and dict comprehensions.

buyers = [
    {'1A' : '1', '1B' : '1', '1C' : '2'},
    {'2A' : '2', '2B' : '4', '2C' : '3'}
]


result = [
    {key: int(val) for key, val in d.items()}
    for d in buyers
]

print(result)

Output

[{'1A': 1, '1B': 1, '1C': 2}, {'2A': 2, '2B': 4, '2C': 3}]

You need to change i[v] = int(i[v]) to i[k] = int(v)

dict1  = {'1A' : '1', '1B' : '1', '1C' : '2'} 

for k, v in dict1.items():
    dict1[k] = int(v)
print(dict1 )

output:

{'1A': 1, '1B': 1, '1C': 2}
Related