Avijit Ashe
Avijit Ashe

Reputation: 33

Importing CSV Data As Variable-Value Pairs in Python

I'm trying to emulate the bash concept in Python to have data from a CSV as variable-value pairs. I've a CSV file, which can be made anyway as possible (its up to me). Currently it looks like this...

Unit,pixels
AvgVol,87654
AvgLen,5432

and similarly a long list of values. If modifying the CSV will make it work, do suggest that too.

I'm trying to read these in such a way that I can access the values like pixels using Unit or 87654 using AvgVol without having to remember their index, similar to what cat or source would do in bash. Anyways, This is useful so that I can edit my CSV file with the list of variables and their values, without having to worry about their order or anything when referring to a particular variable for its values. I'll later use these for other computations so I can go like

if AvgVol>MaxVol:
   print 'something'

Any help is appreciated and I hope its doable without much complexity. Thanks!!

Upvotes: 0

Views: 93

Answers (1)

riteshtch
riteshtch

Reputation: 8769

You can use the csv module to perform your task.

Here is an example:

$ cat csvfile 
Unit,pixels
AvgVol,87654
AvgLen,5432
$ python3 script.py 
{'Unit': 'pixels', 'AvgLen': 5432, 'AvgVol': 87654}

and here is the python program:

import csv

csvdict={}
with open('csvfile', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        csvdict[row[0]]=(int(row[1]) if row[1].isdigit() else row[1])

print(csvdict)

Upvotes: 1

Related Questions