1

guys i couldn't solve this problem... I have a file 'text.CSV' like this:

milk,2.35
bread , 1.95
 chips ,    2.54
milk  ,    2.38
milk,2.31
bread,    1.90

def takes file and it should return this:

[('bread', '$3.85'), ('chips', '$2.54'), ('milk', '$7.04')]

How can i do that? i tried different ways!but i couldn't solve it My solution:

def calculate_expenses(filename):
    file_pointer = open(filename, 'r')
    data = file_pointer.readlines()
    f=[]
    f2=[]
    for i in data:
        x=i.split(',')
        for j in x:
            a=x[0].strip()
            b=x[1].strip()
            a=a.strip('\n')
            b=b.strip('\n')
            b=b.split()
            b.insert(0,'$')
            b="".join(b)
            f.append(a)
            f.append(b)
            f2.append(f)
            f=[]
            break
    return f2
filename='text.CSV'
print(calculate_expenses(filename))

it returns:

[['milk', '$2.35'], ['bread', '$1.95'], ['chips', '$2.54'], ['milk', '$2.38'], ['milk', '$2.31'], ['bread', '$1.90']]

can anybody help me?

3 Answers3

1
def calculate_expenses(filename):
    d= {}
    file_pointer = open(filename, 'r')
    data = file_pointer.readlines()
    for line in data:
        line = line.strip().split(',')
        my_item = line[0].strip()
        my_price = float(line[1].strip())

        if my_item not in my_dictionary:
            d[my_item] =  my_price
        else:
            d[my_item] +=  my_price
    l= []
    my_keys = sorted(d.keys())
    for x in my_keys:
        l.append((x,"${0:.2f}".formatd[x])))
    return l
0

The easiest way is to use a dictionary : everytime you will encounter a line, you will check if the value is in the dictionary, and create it if it is not. Then you will add the values.

def calculate_expenses(filename):
    #your dict of results :
    dres={}
    file_pointer = open(filename, 'r')
    data = file_pointer.readlines()
    f=[]
    f2=[]
    for i in data:
        x=i.split(',')
        a=x[0].strip()
        b=x[1].strip()
        a=a.strip('\n')
        b=b.strip('\n')
        if a not in dres:
            dres[a]=0
        dres[a]+=float(b)
        f2=[]
        #outputting the correct format : as an array of tuples
        for k in dres.keys():
            f2+=[(k,'${:.2f}'.format(dres[k]))]
    return f2
filename='text.CSV'
print(calculate_expenses(filename))
WNG
  • 3,705
  • 2
  • 22
  • 31
  • if we remove b=b.split()..... def return [('milk', '$14.08'), ('bread', '$7.70'), ('chips', '$5.08')] we need [('bread', '$3.85'), ('chips', '$2.54'), ('milk', '$7.04')] –  Aug 04 '17 at 16:19
  • my script returns you 14.08 with the file in your example ? It seems the products are counted twice, are you sure they are not repeated in your source file ? I removed the b.split() that was indeed a remnant of your old code that made it wrong – WNG Aug 04 '17 at 17:13
0

If you're not opposed to using pandas:

import pandas as pd

df = pd.DataFrame.from_csv('text.csv',index_col=None,header=None)
df[0] = df[0].apply(lambda x:x.strip())
df = df.groupby(0).sum().reset_index()
mylist = zip(df[0],map(lambda x: '${:.2f}'.format(x),df[1]))
dashiell
  • 812
  • 4
  • 11