Forum Discussion
Anonymous
2 years agoFWIW, I wouldn’t use argparse to pull in the csv data. I’d actually use the built in CSV handling capabilities of Python:
def read_csv(filename):
import csv
result = []
with open(filename, mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
result = [
{"name":row["name"], "department":row["department"], "bday":row["birthday month"]}
for row
in csv_reader
]
return result
Given the following CSV file called “example.csv” in the current working directory:
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
The usage would look like this:
>>> from pprint import pprint
>>> def read_csv(filename):
... import csv
... result = []
... with open(filename, mode='r') as csv_file:
... csv_reader = csv.DictReader(csv_file)
... result = [
... {"name":row["name"], "department":row["department"], "bday":row["birthday month"]}
... for row
... in csv_reader
... ]
... return result
...
>>> data = read_csv("example.csv")
>>> pprint(data)
[{'bday': 'November', 'department': 'Accounting', 'name': 'John Smith'},
{'bday': 'March', 'department': 'IT', 'name': 'Erica Meyers'}]
>>>