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.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 13 views 0 copies

Python code

22 lines
Python 3.9+
def 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

stdout
{'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

  1. Use a single try/except with a helper that attempts int then float, for slightly cleaner code.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.