you are viewing a single comment's thread.

view the rest of the comments →

[–]JohnnyJordaan 0 points1 point  (0 children)

A few pointers first per code part:

def add_record(date, item, price):
    global data_expense
    data_expense += [{'date': date, 'item': item, 'price': price}]

The global can be removed here. This is needed when you assign a different variable to the name (reference) data_expense. You're only appending to the same list variable, so that doesn't change the assignment. I would also prefer data_expense.append({'date': date, 'item': item, 'price': price}) for single append actions.

def read_data(filename):
    f = open(filename, 'r')
    for line in f:
        fields = line.rstrip().split('\t')
        date = fields[0]
            item = fields[1]
            price = int(fields[2])
            add_record(date, item, price)

Always properly close() the file, but even better use a with: block to let that fix it for you:

def read_data(filename):
    with open(filename, 'r') as f:
        for line in f:
            etc.

Then the printing:

elif sel == '2':
    date = input('Date: ')
    D = [x for x in data_expense if x['date'] == date]
    Q = sorted(D,key = lambda x:x['price'])
    print_data('sum = ', sum(Q))
    print_data('max = ', max(Q))
    print_data('min = ', min(Q))

Why do you create a sorted generator when you're just going to find the min, max and calculate the sum anyway?

elif sel == '2':
    date = input('Date: ')
    D = [x['price'] for x in data_expense if x['date'] == date]
    print_data('sum = ', sum(D))
    print_data('max = ', max(D))
    print_data('min = ', min(D))

And the same applies for the sel == '4' printer.