Search code examples
pythonpython-3.xsum

How to calculate the sum for each customer ID?


I want to create a function that outputs the following for a given dictionary in Python:

Date : 20150102
Status : processing

Customer ID 1
- Order 1000000001 => 105.5
- Total => 105.5

Customer ID 2
- Order 100000000111 => 100.5
- Order 10000000011 => 15.5
- Total => 116

I have made the exercise except for the total part. I am simply unable to calculate the amount for each customer_id.

Here is my code:

def display(date, status, orders):
    sum_order = 0
    # Print the list of sales:
    for i in orders:
        if (orders[i]['date']) == date:
            if (orders[i]['status']) == status:
                print("Customer ID: ", orders[i]['customer_id'])
                print("- Order {} => {} euros".format(i, orders[i]['amount']))
        sum_order += orders[i]['amount']
        print("total = ", sum_order)


orders = {
'100000000111': {
'status': 'processing',
'customer_id': 2,
'amount': 100.50,
'date': 20150102
},
'1000000001': {
'status': 'processing',
'customer_id': 1,
'amount': 105.50,
'date': 20150102
},
'10000000011': {
'status': 'processing',
'customer_id': 2,
'amount': 15.50,
'date': 20150102
},
};


date = int(input("What date? "))
status = input("Complete or Processing? ")
print(display(date, status, orders))

Is it possible to actually solve this problem, and if yes, what would be the solution and why?


Solution

  • This will work fine:

    def display(date, status, orders):
        sum_order = 0
        temp={}
        # Print the list of sales:
        for k,v in orders.items():
    
            if(v['date']==date):
                if(v['status']==status):
                    if v['customer_id'] in temp:
                        temp[v['customer_id']].append([k,v['amount']])
                    else:
                        temp[v['customer_id']]=[[k,v['amount']]]
        for id in sorted(temp):
            print("Customer ID: ", id)
            total=0
            for stuff in temp[id]:
                print("- Order {} => {} euros".format(stuff[0], stuff[1]))
                total+=float(stuff[1])
            print("total = ", total)
        return
    
    
    orders = {
    '100000000111': {
    'status': 'processing',
    'customer_id': 2,
    'amount': 100.50,
    'date': 20150102
    },
    '1000000001': {
    'status': 'processing',
    'customer_id': 1,
    'amount': 105.50,
    'date': 20150102
    },
    '10000000011': {
    'status': 'processing',
    'customer_id': 2,
    'amount': 15.50,
    'date': 20150102
    },
    };
    
    
    date = int(input("What date? "))
    status = input("Complete or Processing? ")
    
    display(date, status, orders)