2021年4月29日星期四

Python - Check all the key - value pairs in a dict and convert to int or float

Let's say I have a dict like this:

[{'Chr': 'chrX', 'Start': '107844640', 'End': '107844640'}]  

Almost all the key values are strings, not all of them, but almost (I don't know why).

I would like to check all the key values and convert the strings to int or float only if the string contains numbers. '10.020' should be a float, '10.020abc' should remain as a string and '123' should be an int.

This is the desired result:

[{'Chr': 'chrX', 'Start': 107844640, 'End': 107844640}]  

I did something similar in JavaScript with Number().

Is there any pythonic way to achieve that?

https://stackoverflow.com/questions/67327043/python-check-all-the-key-value-pairs-in-a-dict-and-convert-to-int-or-float April 30, 2021 at 09:24AM

没有评论:

发表评论