Python Practice › Dictionary Programs › Program 60
Convert string values to numbers
Write a Python program to convert the string values of a dictionary to int or float.
Input
{"a": "30", "b": "20", "c": "10"}, {"a": "3.33", "b": "20.50", "c": "12.5"}Output
{'a': 30, 'b': 20, 'c': 10}
{'a': 3.33, 'b': 20.5, 'c': 12.5}Approach
- Use
intwhen the text has no decimal point, otherwisefloat.
Solution
def to_number(text): return float(text) if "." in text else int(text) for d in [{"a": "30", "b": "20", "c": "10"}, {"a": "3.33", "b": "20.50", "c": "12.5"}]: print({k: to_number(v) for k, v in d.items()})Output
{'a': 30, 'b': 20, 'c': 10}
{'a': 3.33, 'b': 20.5, 'c': 12.5}Learn the concept
New to this topic? Read the lesson, then come back.