Convert string values to numbers

EasyDictionary Programs · 60 of 94

Write a Python program to convert the string values of a dictionary to int or float.

Advertisement
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

  1. Use int when the text has no decimal point, otherwise float.

Solution

Python
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.

More dictionary programs

← All 94 Dictionary Programs

Leave a Comment