P
P
PyCi2022-03-16 10:59:33
Python
PyCi, 2022-03-16 10:59:33

How to work with a string in python according to the principle of csv format?

You need to write a function that will take csv files or a csv style string and translate it into a dict.
There are no problems with the first one, since python has csv.DictReader.

class CSVParser:

    def parse(self, data: str) -> list:
        """Parses input str data into dict."""
        result = []
        for row in csv.DictReader(data):
            result.append(row)
        return result


How do I work with a line like this one?
data = """
    a, b, c
    1, 2, 3
    1.1, 2.2, 3.3
"""

x = CSVParser()
x.parser(data)

At the output I want to get:
[{'a': '1', 'b': '2', 'c': '3'}, {'a': '1.1 ', 'b': '2.2', 'c': '3.2'}]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dr. Bacon, 2022-03-16
@bacon

Ok Google, "python csv read from string"

P
PyCi, 2022-03-16
@PyCi

import csv
from io import StringIO

class CSVParser:

    def parse(self, data: str) -> list:
        """Parses input str data into dict."""
        result = []
        reader_list = csv.DictReader(StringIO(data))
        for row in reader_list:
            result.append(row)
        return result

Answer!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question