rGun rGun - 1 year ago 85
Python Question

Trying to convert all values in a dictionary to int through dictionary comprehension

I have a dictionary like this:

{1: 'rattle', 2: '204', 3: 'three', 4: 404, 5: '104', 6: 'pythonic'}

And I want to convert all values to integer, wherever possible, through dictionary comprehension. So I want this:

{1: 'rattle', 2: 204, 3: 'three', 4: 404, 5: 104, 6: 'pythonic'}

I tried:

{i: int(m[i]) for i in m if type(m[i]) == str and m[i].isdigit()}

but it includes only those values which are string and can be converted to integer. I have also tried putting the whole thing in a try catch, but it doesn't work

I know this can be done through a simple for loop but is there any other way?

Answer Source

By adding an if to the end of your loop, you are filtering, limiting your output to key-value pairs where the value is a string and consists of digits.

Use a conditional expression in the value expression instead; that way you keep all key-value pairs but only apply int() to values where this matters and include the rest unchanged:

{k: int(v) if isinstance(v, str) and v.isdigit() else v for k, v in m.items()}

Rather than just iterate over m (and only get the keys), I used dict.items() to get both the key and the corresponding value in one step.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download