Home > other >  How to store a full column from a csv as a dictionary value?
How to store a full column from a csv as a dictionary value?

Time:12-06

I want to store one or multiple columns of a csv (without delimiter, header and index) as a value in a dictionary.

Example:

csv: 
numbers
17
28
93 
14
5

dictionary:
"foo":  {
             17
             28
             93 
             14
             5
         }

Is there a way to achieve this?

CodePudding user response:

I would use pandas for this but it might be abit of an overkill.

import pandas as pd
dictionary = pd.read_csv('/tmp/t.csv').to_dict()
dictionary

{'numbers': {0: 17, 1: 28, 2: 93, 3: 14, 4: 5}}

CodePudding user response:

How about just read your csv file, split on '\n' and (assuming the first line is the word "numbers" that you don't want) store it in a dictionary:

d = {'foo': open('your_csv_file.csv', 'r').read().split('\n')[1:]}

If there are multiple columns (assuming it is columns are comma-separated):

lst = open('your_csv_file.csv', 'r').read().split('\n')
dct = {k:[] for k in lst[0].split(',')}
for l in lst[1:]:
    for k,x in zip(dct, l.split(',')):
        dct[k].append(x)
  • Related