def parse_csv(text): | |
"""Parses a CSV format text, returns a dictionary, keys are the Column headers from the CSV and values are the data""" | |
result = {} | |
# first split by EOL | |
lines = text.split("\n") | |
if len(lines) > 0: | |
headers = [item.strip() for item in lines[0].split(",")] | |
# rows | |
for line in lines[1:]: # bypass first line, that contains the header | |
row_items = [item.strip() for item in line.split(",")] | |
counter = 0 | |
for header in headers: | |
if header not in result: | |
result[header] = [] | |
result[header].append(row_items[counter]) | |
counter += 1 | |
return result | |
if __name__ == "__main__": | |
sample_csv = """Column1, Column2, Column3 | |
1, 2, 3 | |
a, b, c | |
I, V, X | |
4, 5, 6 | |
d, e, f""" | |
parsed_data = parse_csv(sample_csv) | |
print(parsed_data) # will print {'Column1': ['1', 'a', 'I', '4', 'd'], 'Column3': ['3', 'c', 'X', '6', 'f'], 'Column2': ['2', 'b', 'V', '5', 'e']} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment