Home > database >  How to change the values of dictionary from string to int if they are in a list
How to change the values of dictionary from string to int if they are in a list

Time:03-24

I have a dictionary as

maketh = {'n':['1', '2', '3'], 'g': ['0', '5', '6', '9'], 'ca': ['4', '8', '1', '5', '9', '0']}

which I intend to change to

maketh_new = {'n':[1, 2, 3], 'g': [0, 5, 6, 9], 'ca': [4, 8, 1, 5, 9, 0]}

The order in which the numbers are in the values are very important. So, the order should remain the same even after they are changed.

The error I always get when I try to change it using any method available online is:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

"If there is any typing mistake pls ignore it..."

One that I wrote on my own thinking that may be something like this can work was:

maketh_new = dict()

for (key, values) in maketh.items():
    for find in len(values):
        maketh_new [key] = int(values[find])   

I tried it thinking if I can access all the elements of the values that are in the list as a string then I may be able to type caste it into int. But I get an error as:

'list' object cannot be interpreted as an integer 

So if someone can help me find a solution, please do it...

CodePudding user response:

Assuming all elements in the values are digits, you can map int on the values:

maketh_new = {k: list(map(int, v)) for k, v in maketh.items()}

Output:

{'n': [1, 2, 3], 'g': [0, 5, 6, 9], 'ca': [4, 8, 1, 5, 9, 0]}

If not, you can use str.isdigit for safer typing:

maketh = {'n':['1', '2', 'a'],  # Note 'a' at last
          'g': ['0', '5', '6', '9'], 
          'ca': ['4', '8', '1', '5', '9', '0']}

maketh_new = {k: [int(i) if i.isdigit() else i for i in v] for k, v in maketh.items()}

Output:

{'n': [1, 2, 'a'], 'g': [0, 5, 6, 9], 'ca': [4, 8, 1, 5, 9, 0]}
  • Related