1

I have a csv file which looks like this

   header1   header2   header3
1  value1    value2    value3
2  value4    value5    
3            value6    value7

And I would like to make a dict which will look like this:

{header1:[value1, value4],
header2:[value2, value5, value6],
header3:[value3, value7]

}

I already tried

records = csv.DictReader(f)
    for row in records:
         print(row)

But It takes first column values as keys in dict what could I do?

  • Does this answer your question? [Creating a dictionary from a csv file?](https://stackoverflow.com/questions/6740918/creating-a-dictionary-from-a-csv-file) – Maurice Meyer Jan 10 '20 at 08:04
  • Unfortunately, the answers in the nominated duplicate all seem to replace any previous value, not build lists of values for each key. – tripleee Jan 10 '20 at 08:05

3 Answers3

2

Here's one quick and I hope obvious way.

from csv import DictReader
from collections import defaultdict

result = defaultdict(list)
records = DictReader(f)
for row in records:
     for key in row:
         result[key].append(row[key])
tripleee
  • 175,061
  • 34
  • 275
  • 318
0

You can use pandas for this.

import pandas as pd
df = pd.read_csv("Your CSV file name")
dict1 = df.to_dict('list')
print(dict1)
Gaurav Agarwal
  • 611
  • 6
  • 18
  • If you (plan to) use Pandas anyway, this is terrific. If not, it's huge overkill. – tripleee Jan 10 '20 at 08:13
  • The person who posted the question did not mention relevant info actually. Also, it's not too unfair to assume that pandas would be involved while dealing with CSVs right? – Gaurav Agarwal Jan 10 '20 at 08:15
  • Why do you think Pandas is required for CSV files? If you want to do calculations or analytics then Pandas is a great tool; but again, if not, it's a massive package which you will only use a tiny part of. – tripleee Jan 10 '20 at 08:16
  • I didn't say required. I just meant to say that it shouldn't directly be ruled out. Lots of data scientists often export query results to CSVs and perform analytics. The person asking this question didn't specify his intention so I posted an answer with pandas as well. – Gaurav Agarwal Jan 10 '20 at 08:19
  • Right, and you didn't explain when it would be a good idea, so I added a comment to hopefully clarify that. It would be silly for them to go and install Pandas just for this. – tripleee Jan 10 '20 at 08:20
  • 1
    Oh yeah. Thanks. I'm just getting started on SO so am still figuring out how much detail is too much. – Gaurav Agarwal Jan 10 '20 at 08:22
0

use pandas dataframe to read csv and convert to dict

import pandas as pd
df = pd.read_csv('test2.csv', sep=',')
df.to_dict('list')

It gives the below output.

{
'header1': ['value1', 'value4', nan],
 'header2': ['value2', 'value5    ', 'value6'],
 'header3': ['value3', nan, 'value7']
}
Prince Francis
  • 2,995
  • 1
  • 14
  • 22