How to Convert Data Types in Python with a Helper Class

This code defines a beginner-friendly OOP helper class for common data conversions like string to list, list to dict, JSON string, and CSV row, with an advanced subclass for numeric casting.

Easy Python 3.9+ Aug 9, 2026 OOP & classes 14 views 0 copies

Python code

51 lines
Python 3.9+
class DataConverter:
    """A beginner-friendly helper class for common data conversions."""
    
    def __init__(self, data):
        self.data = data
    
    def to_list(self):
        """Convert string data (comma-separated) to a list."""
        if isinstance(self.data, str):
            return [item.strip() for item in self.data.split(",")]
        return list(self.data)
    
    def to_dict(self, keys):
        """Convert two lists into a dictionary (keys and values)."""
        values = self.to_list()
        return dict(zip(keys, values))
    
    def to_json_string(self):
        """Convert data to a JSON-formatted string."""
        return json.dumps(self.data)
    
    def to_csv_row(self):
        """Convert list data to a CSV row string."""
        items = self.to_list()
        return ",".join(str(item) for item in items)


class AdvancedConverter(DataConverter):
    """Extended converter with numeric type casting."""
    
    def to_numbers(self):
        """Convert string data to a list of integers."""
        return [int(item) for item in self.to_list()]
    
    def to_floats(self):
        """Convert string data to a list of floats."""
        return [float(item) for item in self.to_list()]


if __name__ == "__main__":
    import json
    
    raw_data = "10, 20, 30, 40"
    converter = AdvancedConverter(raw_data)
    
    print("List:", converter.to_list())
    print("Numbers:", converter.to_numbers())
    print("Floats:", converter.to_floats())
    print("CSV row:", converter.to_csv_row())
    print("JSON:", converter.to_json_string())
    print("Dict:", converter.to_dict(["a", "b", "c", "d"]))

Output

stdout
List: ['10', '20', '30', '40']
Numbers: [10, 20, 30, 40]
Floats: [10.0, 20.0, 30.0, 40.0]
CSV row: 10,20,30,40
JSON: "10, 20, 30, 40"
Dict: {'a': '10', 'b': '20', 'c': '30', 'd': '40'}

How it works

The DataConverter class stores raw data in self.data and provides conversion methods that reuse the to_list() method to avoid duplication. The AdvancedConverter subclass extends the base class with type-casting methods, demonstrating inheritance. Each method returns a new object, keeping the original data unchanged. The code runs the demo only when executed directly, using the if __name__ == "__main__" guard.

Common mistakes

  • Forgetting to import `json` before using `json.dumps` in the class
  • Assuming `to_list()` always returns strings when input is a list of numbers
  • Passing mismatched key and value lengths to `to_dict`, causing silent truncation

Variations

  1. Use a `@staticmethod` or classmethod instead of instance methods for stateless conversions
  2. Add a `to_tuple()` method returning `tuple(self.to_list())`

Real-world use cases

  • Normalizing raw CSV lines from a file into Python lists for further processing.
  • Converting API response strings into structured dictionaries for your application.
  • Casting user input strings to numeric types for calculations in a CLI tool.

Sponsored

Run this sample

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

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.