I want to write from a csv file to a dictionary.
But:
My code so far:
def coordinates(text):
import csv
reader = csv.reader(open(text))
d = {}
for row in reader:
key = row[0]
d[key] = row[1:]
print(d)
coordinates('luchthavens2.csv')
With this code all items from the row are the key in my dictionary.
Who can help?
EDIT:
Input file looks like this:
BIN,"Bamiyan","Bamiyan","Afghanistan","AF",34.800000,67.816667,701,"Afghanistan",\N,\N,1149361
BST,"Bost","Bost","Afghanistan","AF",31.550000,64.366667,701,"Afghanistan",\N,1134720,1149361
CCN,"Chakcharan","Chakcharan","Afghanistan","AF",34.533333,65.266667,701,"Afghanistan",\N,\N,1149361
All from an excel file called luchthavens2.csv, the positions of the text are A1-A2-A3-etc.
You should find it here: https://expirebox.com/download/bb8cb3a39f9be041743a8b86db89093b.html
Output:
{
'CCN,"Chakcharan","Chakcharan","Afghanistan","AF",34.533333,65.266667,701,"Afghanistan",\\N,\\N,1149361': [],
'BST,"Bost","Bost","Afghanistan","AF",31.550000,64.366667,701,"Afghanistan",\\N,1134720,1149361': [],
'BIN,"Bamiyan","Bamiyan","Afghanistan","AF",34.800000,67.816667,701,"Afghanistan",\\N,\\N,1149361': []
}
EDIT:
I've changed my input file to a text file, then back again to a csv file. Strangely enough this worked, I can read it without any problems.
If you run the following,
import pprint
import csv
def coordinates(text):
ret = {}
with open(text, 'r') as fp:
reader = csv.reader(fp)
for row in reader:
key = row.pop(0)
ret[key] = row
return ret
data = coordinates('data.csv')
pprint.pprint(data)
On the following file,
$ cat data.csv
AAA,"Blub",25.25
BBB,"Blob",27.27
Then you will get,
$ python stackoverflow.py
{'AAA': ['Blub', '25.25'], 'BBB': ['Blob', '27.27']}
In your input file, the quotation marks are messed up.
"BIN,""Bamiyan"",""Bamiyan"",""Afghanistan"",""AF"",34.800000,67.816667,701,""Afghanistan"",\N,\N,1149361"
"BST,""Bost"",""Bost"",""Afghanistan"",""AF"",31.550000,64.366667,701,""Afghanistan"",\N,1134720,1149361"
"CCN,""Chakcharan"",""Chakcharan"",""Afghanistan"",""AF"",34.533333,65.266667,701,""Afghanistan"",\N,\N,1149361"
should be
"BIN","Bamiyan","Bamiyan","Afghanistan","AF",34.800000,67.816667,701,"Afghanistan",\N,\N,1149361
"BST","Bost","Bost","Afghanistan","AF",31.550000,64.366667,701,"Afghanistan",\N,1134720,1149361
"CCN","Chakcharan","Chakcharan","Afghanistan","AF",34.533333,65.266667,701,"Afghanistan",\N,\N,1149361
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