For example, say my data is in the form:

Column A,Column B
Cell 1,Cell 2
Cell 3,Cell 4

and I want to end up with several dictionaries that look like:

{"Column A":"Cell 1", "Column B":"Cell 2"}
{"Column A":"Cell 3", "Column B":"Cell 4"}
{"Column A":"Cell 5", "Column B":"Cell 6"}

The csv file I'm using has several named columns, and I want to basically print a dictionary using the column header as the key, with it's associated cell as the value. Right now I seem to be stuck either printing a dictionary like:


{"Column A":"Cell 1", "Cell 2"}

or just being able to get a dictionary for one value like:

{"Column A":"Cell 1"}

I've looked up similar problems on here already, but I'm still new to python and can't seem to figure out the answer for this specific problem.

with open('file_name.csv') as filename:
    linelist = []
    output_dict = {}
    for i in filename:
        linelist.append(i.split(","))
        for line in linelist:
            header = linelist[0]
            value = linelist[1:]
            for j in line:
                output_dict.update({header[0]:line[0]})

At this point this is what I have, but I've just been aimlessly trying to add and take away parts of it so this doesn't even work now.

1

There are 1 best solutions below

2
On

I would do it following way, let file.csv content be

columnA,columnB
cell1,cell2
cell3,cell4

then

with open("file.csv", "r") as f:
    headers = next(f).strip().split(",")
    for line in f:
        print(dict(zip(headers,line.strip().split(","))))

gives output

{'columnA': 'cell1', 'columnB': 'cell2'}
{'columnA': 'cell3', 'columnB': 'cell4'}

Explanation: firstly I create list of headers, to do so I instruct python to consume 1st line (next(f)), remove leading and trailing whitespace characters (.split()) and split at commas. For each following line I do same thing to given line and then use dict-zip to create dictionary from two lists, where elements at same position in each list are key value pair.