Python Forum
[SOLVED] Filling multidict from CSV file?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[SOLVED] Filling multidict from CSV file?
#1
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.
Reply
#2
please provide a sample of input.csv
Reply
#3
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.
Reply
#4
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Solved] Plotting data from txt file Laplace12 1 188 Jul-06-2021, 07:14 AM
Last Post: Laplace12
  [Solved] Reading every nth line into a column from txt file Laplace12 7 461 Jun-29-2021, 09:17 AM
Last Post: Laplace12
  [Solved] Trying to read specific lines from a file Laplace12 7 507 Jun-21-2021, 11:15 AM
Last Post: Laplace12
  [Solved] Using readlines to read data file and sum columns Laplace12 4 303 Jun-16-2021, 12:46 PM
Last Post: Laplace12
  filling and printing numpy arrays of str pjfarley3 4 876 Jun-07-2020, 09:09 PM
Last Post: pjfarley3
  TypeError: size; expecting a recognized type filling string dict a11_m11 0 824 Feb-10-2020, 08:26 AM
Last Post: a11_m11
  Filling an Excel file starter_student 3 1,402 Jul-05-2019, 06:29 AM
Last Post: starter_student
  Cage filling algorithm - Python bnbehera 3 1,676 Jul-02-2018, 04:55 PM
Last Post: ichabod801
  netCDF issue with filling a variable HeavyLoads 1 3,348 Oct-03-2016, 08:34 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020