Phang Weijun
Phang Weijun

Reputation: 15

How do I create a function to search within a CSV file?

Write a function that would read a CSV file that looks like this, flowers.csv:

petunia,5.95
alyssum,3.95
begonia,5.95
sunflower,5.95
coelius,4.95

and look up the price of a flower and print out that price.

import csv

def problem3_7(csv_pricefile, flower):

  f = open(csv_pricefile) 

  for row in f:
    if row[0] == flower:
      print (row[1])    

  f.close() 

I considered converting the CSV file into a dictionary so that by searching a flower it would give the price. I do believe there's a better way to do this by comparing the rows but I just can't seem to figure out how.

A row would consist of e.g petunia, 5.95 and not just petunia which means I cannot compare the rows == flower. I tried using row[0][0] since it refers to only the name of the flower but it didn't really work for me.

And... I think I should be using some csv functions which I am currently not doing so.

Could someone help me out with this?

Upvotes: 1

Views: 516

Answers (4)

alvaro nortes
alvaro nortes

Reputation: 630

import pandas as pd                                                              

src = "/path/to/data.csv"                                       
df = pd.read_csv(src, names=["flower","price"])                                  
print df                                                                         
#       flower  price                                                            
# 0    petunia   5.95                                                            
# 1    alyssum   3.95                                                            
# 2    begonia   5.95                                                            
# 3  sunflower   5.95                                                            
# 4    coelius   4.95                                                            

# Retrieve the row with a flower called petunia                                  
row_result = df.loc[df['flower'] == 'petunia']                                   
print row_result                                                                 
#     flower  price                                                              
# 0  petunia   5.95                                                              

# Retrieve the price of the first row                                            
if row_result:                                                                   
    price = row_result.iloc[0]['price']                                          
    print price                                                                  
    # 5.95                                                                       
else:                                                                            
    print "Not Found"                                                            

Upvotes: 0

ndrewl
ndrewl

Reputation: 142

You can use pandas like this:

import pandas as pd
with open(csv_pricefile, 'r') as pricefile:
    df = pd.read_csv(pricefile, names=['flower', 'price'], index_col=0)
    data = df.to_dict(orient='index')
    # now you can get the price
    print(data[flower]['price'])

Upvotes: 0

jpp
jpp

Reputation: 164663

You can use csv.reader and a dictionary comprehension to construct a mapping between flower name and price:

from io import StringIO
import csv

mystr = StringIO("""petunia,5.95
alyssum,3.95
begonia,5.95
sunflower,5.95
coelius,4.95""")

# replace mystr with open(csv_pricefile)
with mystr as fin:
    reader = csv.reader(fin)
    flower_prices = {name: float(price) for name, price in reader}

print(flower_prices)

{'alyssum': 3.95,
 'begonia': 5.95,
 'coelius': 4.95,
 'petunia': 5.95,
 'sunflower': 5.95}

Then extract the price of a specific flower via the dictionary, e.g. for petunia use flower_prices['petunia'].

Upvotes: 2

Sianur
Sianur

Reputation: 649

You are comparing flower with the first character, not component. Try using:

    for row in f:
        cols = row.split(',')
        if cols[0].strip() == flower:
            print (cols[1].strip())    

Upvotes: 0

Related Questions