1

I have this CSV:

color,property,type,id
red,house,building,02 

I'm trying to convert a csv to dictionary with the following structure:

{
"0": {"val1": 1, "val2": 2, "val3": 3, ..., "valn": n},
"1": {"val1": 45, "val2": 7, "val3": None, ..., "valn": 68},
}

Where as val1, val2 and so on are the header names of the columns and "0" and "1" are the number of rows.

So we should have:

CSV content is like this:

color,property,type,id
red,house,building,02 
blue,department,flat,04

{
"0": {"color": "red", "property": "house", "type": "building", ..., "valn": n},
"1": {"color": "blue", "property": "farm", "type": "area", ..., "valn": n},
}

How can I achieve this result without using any library? I'd like to implement it from the scratch and don't use CSV library or the like.

Thank you.

js352
  • 364
  • 2
  • 9

1 Answers1

0

Try this approach:

inp = """color,property,type,id
red,house,building,02 
blue,department,flat,04
cyan,,flat,10
"""

lines = inp.split('\n')

colnames = list(map(lambda x: x.strip(), lines[0].split(',')))
lines = lines[1:]
res = {}

for i, line in enumerate(lines[:-1]):
    res[i] = {
        colname: val if val != '' else None 
        for colname, val in zip(colnames, map(lambda x: x.strip(), line.split(',')))
    }

print(res)

However for additional features like type deduction code will be more complex: you can follow answers to this question

nik7
  • 806
  • 3
  • 12
  • 20