Home > Enterprise >  How can I convert a list of strings within a dictionary's values to int?
How can I convert a list of strings within a dictionary's values to int?

Time:01-18

I have a Python dictionary with keys that are strings, and values that are lists of numbers which are also strings. I'd like to convert the numbers to int, but am having some trouble. Just to illustrate, I'd like to change:

d = {'a': ['1', '2', '3'], 'b': ['4', '5', '6'], 'c': ['7', '8', '9']}

into

d = {'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}

CodePudding user response:

Use the following code.

for key in d.keys():
    d[key] = list(map(int, d[key]))

CodePudding user response:

I would have commented this out but unfortunately, I am new to Stack Overflow and don't have enough reputation. But based on @pranav-hosangadi suggestion you can just do it in a single line.

d = {key: list(map(int, value)) for key, value in d.items()}
  • Related