Eva Kontogianni
Eva Kontogianni

Reputation: 1

How to Extract Data from CSV file and import to a Dictionary in Python?

I'm new in python new developer, just started my intership. So, I have a csv file with datas customized like that

Event Category,Event Label,Total Events,Unique Events,Event Value,Avg. Value

From each row of the file I want to extract the labels of the ports (bellow) in an dictionary and add the total and unic events too. The total and unique events I have to sum them only the ports with same labels (not being dublicate). My datas look like that : 'Search,Santorin (JTR) - Paros (PAS) - Santorin (JTR),"2,199","1,584",0,0.00' I want my dictionary to look like that :

data_file = 'Analytics.csv' ports_dict = { # "ATH-HER" : [10000, 5000], # "ATH-JTR" : [20000, 3500], # "HER-JTR" : [100, 500] }

 data = 'Analytics.csv'
#row= 'Search,Santorin (JTR) - Paros (PAS) - Santorin (JTR),"2,199","1,584",0,0.00'
def extract_counts(data):
  ports = []
  for i in data.split('"')[1:]:
      ports.append(i.split('"')[0])
  return ports

An example from my code is this , when I'm running with the row runs ok when I'm using 'data' it gives me back an empty string. Can Anyone help me with this ?

extract_counts(data) Out[13]: []

What I have to do to run this for the whole csv Thank you for your help!

Upvotes: 0

Views: 450

Answers (1)

Karol Adamiak
Karol Adamiak

Reputation: 149

First of all, 'data' is just a string variable. In your loop, you are iterating over each character, not reading a file. Using split on a single character with '"', results in an empty string.

To begin your journey with reading CSV files in Python, I recommend:

Upvotes: 0

Related Questions