Python Forum
[SOLVED] Filling multidict from CSV file? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: [SOLVED] Filling multidict from CSV file? (/thread-30526.html)



[SOLVED] Filling multidict from CSV file? - Winfried - Oct-24-2020

Hello,

For some reason, the list that is filled from the CSV file is OK, but when printing the contents of the multidict, I get more than three values:

from collections import defaultdict

mydict = defaultdict(list)
with open('input.csv", mode='r') as infile:
	reader = list(csv.reader(infile))

	#OK!
	for row in reader:
		#print(row[2],row[5],row[6],row[10])

		#Use ZIP as key, and add multiple values to each key
		mydict[row[2]].append(row[5])
		mydict[row[2]].append(row[6])
		mydict[row[2]].append(row[10])

	#NOK! More than three values!
	for k in mydict:
		print(k,mydict[k])
Can you spot what I'm doing wrong?

Thank you.


RE: Filling multidict from CSV file? - Larz60+ - Oct-24-2020

please provide a sample of input.csv


RE: Filling multidict from CSV file? - Winfried - Oct-24-2020

It's a comma-separated file, eg.

zip,lat,lon,name
12345,46.15,4.92,Some place
FWIW, it opens fine in LibreOffice Calc.


RE: Filling multidict from CSV file? - Winfried - Oct-24-2020

Never mind, pandas worked right off the bat:

import pandas as pd
subset = pd.read_csv(CSVFILE)[["zip", "latitude", "longitude", "name"]]
print(subset.head(8))
Thank you.