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.
Python code
33 linesfrom 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
{'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
- Use the `json.loads` function for actual JSON strings with nested structures and proper type conversion.
- 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
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.