The code I have so far is in a function that basically reads a csv file and prints it's contents:
def read(filename):
with open(filename, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
print(row)
Contents of sailor.csv
:
name, mean performance , std dev
Alice, 100, 0,
Bob, 100, 5,
Clare, 100, 10,
Dennis, 90, 0,
Eva, 90, 5,
read('sailor.csv')
and running the function
current output:
['name', ' mean performance ', ' std dev']
['Alice', ' 100', ' 0', '']
['Bob', ' 100', ' 5', '']
['Clare', ' 100', ' 10', '']
['Dennis', ' 90', ' 0', '']
['Eva', ' 90', ' 5', '']
required output:
{'Dennis': (90.0, 0.0), 'Clare':(100.0, 10.0),
'Eva': (90.0, 5.0), 'Bob': (100.0, 5.0), 'Alice': (100.0, 0.0)}
any ideas how I can achieve that output? Using Python 3.4.2 if that helps, explanation of your answer will be appreciated!
To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.
To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.
DictReader() class can be used to read a CSV file as a dictionary.
using the csv
standard library and a dictionary comprehension...
import csv
with open('sailor.csv') as csvfile:
reader = csv.reader(csvfile)
next(reader)
d = {r[0] : tuple(r[1:-1]) for r in reader}
Where d
will be the dictionary you want. d[1:-1]
slices the array from the second to the second to last element.
EDIT: skips headers, converts to tuples
I think this is what you want:
import csv
def read(filename):
out_dict = {}
with open(filename, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
next(csvfile) # skip the first row
for row in reader:
out_dict[row[0]] = float(row[1]), float(row[2])
print(row)
return out_dict
print(read('data.csv'))
Prints:
{'Bob': (' 100', ' 5'), 'Clare': (' 100', ' 10'), 'Alice': (' 100', ' 0'), 'Dennis': (' 90', ' 0'), 'Eva': (' 90', ' 5')}
Not to much to explain here. Just putting the values in the dictionary, and skipping the first row added. I assumed that the persons names are unique.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With