how to create a dictionary from csv file?
Peter Otten
__peter__ at web.de
Tue Apr 26 10:40:37 EDT 2016
+dime+ wrote:
> I am learning python.
>
> if I have a csv file, like this
> banana,4.0
> apple,3.5
> orange,3.0
>
> Can anyone show me how to read the csv file line by line and then create a
> dictionary to contain these keys and values?
Below is a spoiler, but learning Python is more fun and you'll see success
sooner when you try to come up with a solution yourself, present it here (or
on the tutor mailing list) and let us fill the gaps or suggest improvements.
>>> import csv
>>> with open("fruit.csv") as f:
... lookup = {k: float(v) for k, v in csv.reader(f)}
...
>>> lookup
{'orange': 3.0, 'apple': 3.5, 'banana': 4.0}
>>> 2*lookup["banana"] + 3*lookup["orange"]
17.0
More information about the Python-list
mailing list