0

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!!

1
  • Have a look at DictReader Commented Oct 24, 2016 at 1:00

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.