convert float to int in mixed datatype dictionairy

Viewed 26

bit stuck on something which is probably easy to solve, but all of the examples I found are talking about uniform key:value pairs.

What I want to achieve is the following :

I have a dictionary containing mixed values (strings and floats), and all the floats should be converted to int, otherwise the string is kept.

example :

d = {"key1":"something","key2":200.0, "key3":"another string", "key4":2017.0}

should become :

{"key1":"something","key2":200, "key3":"another string", "key4":2017}

I tried something like this in some variations but no luck

d = {k: int(v) if float(v) else v for k, v in d.items()}

What would be the best approach to achieve this?

1 Answers

Your if float(v) does not check whether v is a float: it only checks if the truthiness of the result of converting v to a float is True. If float(v) raises an exception however, the exception is not catched.

You can use isinstance(..) to check if an object has a certain type:

{k: int(v) if isinstance(v, float) else v for k, v in d.items()}

Which will produce a dictionary like:

>>> {k: int(v) if isinstance(v, float) else v for k, v in d.items()}
{'key2': 200, 'key4': 2017, 'key1': 'something', 'key3': 'another string'}
Related