How to convert string values to int or float in Python dicts
Recursively convert string values in nested dicts and lists to ints or floats when possible, leaving other strings untouched.
Python code
22 linesdef coerce_str_values(data):
"""Recursively convert string values that look like ints or floats."""
if isinstance(data, dict):
return {key: coerce_str_values(val) for key, val in data.items()}
elif isinstance(data, list):
return [coerce_str_values(item) for item in data]
elif isinstance(data, str):
try:
return int(data)
except ValueError:
try:
return float(data)
except ValueError:
return data
else:
return data
if __name__ == "__main__":
sample = {"a": "42", "b": "3.14", "c": "hello", "d": {"e": "7", "f": "2.5"}}
result = coerce_str_values(sample)
print(result)
Output
{'a': 42, 'b': 3.14, 'c': 'hello', 'd': {'e': 7, 'f': 2.5}}
How it works
The function walks the nested structure with isinstance checks, rebuilding dicts and lists item by item. For each string, it first tries int(), then float(), catching ValueError to fall back to the original string. This ordering matters because int('3.14') fails, so floats are handled in the second attempt. The recursion naturally handles arbitrary nesting depth, making the approach reusable for API payloads, config files, or CSV-derived data with mixed types.
Common mistakes
- Checking int() before checking if the value is actually a string — this raises TypeError for non-strings.
- Forgetting that float('2') succeeds but returns 2.0, not 2, which changes output types.
- Not handling lists inside dicts, so nested sequences remain unconverted.
- Assuming all strings convert — strings like 'hello' must fall through unchanged.
Variations
- Use a single try/except with a helper that attempts int then float, for slightly cleaner code.
- Apply the coercion only to top-level dict values when nesting isn't needed.
Real-world use cases
- Cleaning API responses where numeric fields arrive as strings before storing them in a database.
- Processing CSV imports that produce all-string rows, then normalizing numeric columns for analysis.
- Preparing JSON payloads for downstream ML models that expect numeric features rather than strings.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.