Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
82 views
in Technique[技术] by (71.8m points)

python - How to convert value in dictionary from string to int

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.

question from:https://stackoverflow.com/questions/65937789/how-to-convert-value-in-dictionary-from-string-to-int

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...