Search code examples
pythonodoo-12

sort a dictonary in datetime field


hello i have a code that gives me dict the dict here is the dict:

{2516: {'order_date': datetime.datetime(2021, 7, 26, 16, 10, 10, 461000), 'product_id': 2516, 
'product_name': 'TRENTO GRIS 30*60 NEW TILE SPAIN 514', 'quantity': -1.0, 'product_cost': 4.0,
'price_unit': 5.5, 'remaining_qty': -23.0, 'seller_name': 'السيد ابو فهد', 'jour': 'Cash,'},

2412: {'order_date': datetime.datetime(2021, 7, 26, 13, 59, 33, 351000), 'product_id': 2412, 
'product_name': 'ORION HEXA SILVER 19.8*22. SPAIN 355', 'quantity': -4.0, 'product_cost': 0.58, 
'price_unit': 1.25, 'remaining_qty': 129.0, 'seller_name': 'السيد برغش المطيري المحترم ', 'jour': 'Cash,'},

2897: {'order_date': datetime.datetime(2021, 7, 23, 20, 4, 2, 939000), 'product_id': 2897, 'product_name': 'BLANCO BR RECT LA 30*60 SPAIN 456', 
'quantity': -6.0, 'product_cost': 3.5, 'price_unit': 4.0, 'remaining_qty': 6.0, 'seller_name': 'السيد احمد منصور العازمي', 
'jour': 'Cash,'},

 2828: {'order_date': datetime.datetime(2021, 7, 23, 20, 8, 38, 380000), 
'product_id': 2828, 'product_name': 'كاونتر مدور رمادي فاتح 1277 (36*12 CM', 'quantity': -1.0, 'product_cost': 0.0, 
'price_unit': 27.5, 'remaining_qty': -1.0, 'seller_name': 'السيد علي المطيري المحترم', 'jour': 'Cash,'}, 

3041: {'order_date': datetime.datetime(2021, 7, 23, 20, 7, 11, 189000), 'product_id': 3041, 'product_name': 'PRIS TINENZA 30*60 SPAIN', 
'quantity': -2.0, 'product_cost': 5.0, 'price_unit': 6.5, 'remaining_qty': -13.0, 'seller_name': 'السيد محمد حسن الكندري المحترم', 'jour': 'Cash,'}}

i tried list comprenhsion like:

                if products_sold.get(line.product_id.id):
                products_sold[line.product_id.id] = sorted([{
                    'order_date': order.date_order,
                    'product_id': products_sold[line.product_id.id].get('product_id'),
                    'product_name': products_sold[line.product_id.id].get('product_name'),
                    'quantity': products_sold[line.product_id.id].get('quantity', 0) + line.qty,
                    'product_cost': products_sold[line.product_id.id].get('product_cost'),
                    'price_unit': products_sold[line.product_id.id].get('price_unit'),
                    'remaining_qty': line.product_id.qty_available,
                    'seller_name': seller_name,
                    'jour': jour
                } for (product, seller_name, order, line, jour), qty in products_sold.get(line.product_id.id)],key=lambda l: l['order_date']

but each time i try this i get a error "ValueError: too many values to unpack (expected 2)"

I even tried like:

dict = {k: v for k, v in sorted(products_sold[line.product_id.id].items(), key= lambda v : v[0])}

and passed it in return still i get error

how to sort this above dictionary i am getting no idea any help will be appreciated, below is a method in which i want the dict to be sorted by "order_date":

    def get_sale_details_product_wise(self, date_start=False, date_stop=False, configs=False):
    if not configs:
        configs = self.env['pos.config'].search([])

    orders = self.env['pos.order'].search([
        ('date_order', '>=', date_start),
        ('date_order', '<=', date_stop),
        ('state', 'in', ['paid', 'invoiced', 'done']),
        ('config_id', 'in', configs.ids)])

    products_sold = {}
    for order in orders:
        jour = ''
        jour_list = []
        for statement in order.statement_ids:
            if statement.journal_id.name not in jour_list:
                jour_list.append(statement.journal_id.name)
                jour += statement.journal_id.name + ','
        for line in order.lines:
            seller_name = self.env["res.partner"].search(
                [('id', '=', line.order_id.partner_id.id)]).name

            if products_sold.get(line.product_id.id):
                # print('1111111', line.product.id)
                products_sold[line.product_id.id] = sorted([{
                    'order_date': order.date_order,
                    'product_id': products_sold[line.product_id.id].get('product_id'),
                    'product_name': products_sold[line.product_id.id].get('product_name'),
                    'quantity': products_sold[line.product_id.id].get('quantity', 0) + line.qty,
                    'product_cost': products_sold[line.product_id.id].get('product_cost'),
                    'price_unit': products_sold[line.product_id.id].get('price_unit'),
                    'remaining_qty': line.product_id.qty_available,
                    'seller_name': seller_name,
                    'jour': jour
                } for (product, seller_name, order, line, jour), qty in products_sold.get(line.product_id.id)],key=lambda l: l['order_date'])
            else:
                products_sold[line.product_id.id] = {
                    'order_date': order.date_order,
                    'product_id': line.product_id.id,
                    'product_name': line.product_id.name,
                    'quantity': line.qty,
                    'product_cost': line.product_id.standard_price,
                    'price_unit': line.price_unit,
                    'remaining_qty': line.product_id.qty_available,
                    'seller_name': seller_name,
                    'jour': jour
                }
    return {'products': products_sold}

Solution

  • This statement is wrong:

    for (product, seller_name, order, line, jour), qty in products_sold.get(line.product_id.id)
    

    You are iterating the value of products_sold.get(line.product_id.id) and expecting that each item contains a sequence of 5 variables. The value of products_sold.get(line.product_id.id) is a dict:

    whole_dict = products_sold.get(line.product_id.id)  # Let's say id=2412
    print(type(whole_dict), whole_dict)
    

    Output:

    <class 'dict'> {'order_date': datetime.datetime(2021, 7, 26, 13, 59, 33, 351000), 'product_id': 2412, 'product_name': 'ORION HEXA SILVER 19.8*22. SPAIN 355', 'quantity': -4.0, 'product_cost': 0.58, 'price_unit': 1.25, 'remaining_qty': 129.0, 'seller_name': 'السيد برغش المطيري المحترم ', 'jour': 'Cash,'}
    

    Which means that iterating products_sold.get(line.product_id.id) is equivalent to iterating the keys products_sold.get(line.product_id.id).keys() which are just strings:

    for key in products_sold.get(line.product_id.id):  # Equivalent to products_sold.get(line.product_id.id).keys()
        print(type(key), key)
    

    Output:

    <class 'str'> order_date
    <class 'str'> product_id
    <class 'str'> product_name
    <class 'str'> quantity
    <class 'str'> product_cost
    <class 'str'> price_unit
    <class 'str'> remaining_qty
    <class 'str'> seller_name
    <class 'str'> jour
    

    So what you were trying to do is assign each string to those 5 variables:

    (product, seller_name, order, line, jour), qty = "order_date"
    (product, seller_name, order, line, jour), qty = "product_id"
    (product, seller_name, order, line, jour), qty = "product_name"
    # and so on ...
    

    Obviously, they will not fit, which is why you are experiencing the error ValueError: too many values to unpack (expected 2).

    Solution

    Here is how you would sort all the products_sold based on their order_date attribute.

    import datetime
    
    products_sold = {
        2516: {
            'order_date': datetime.datetime(2021, 7, 26, 16, 10, 10, 461000),
            'product_id': 2516,
            'product_name': 'TRENTO GRIS 30*60 NEW TILE SPAIN 514',
            'quantity': -1.0,
            'product_cost': 4.0,
            'price_unit': 5.5,
            'remaining_qty': -23.0,
            'seller_name': 'السيد ابو فهد',
            'jour': 'Cash,'
        },
        2412: {
            'order_date': datetime.datetime(2021, 7, 26, 13, 59, 33, 351000),
            'product_id': 2412,
            'product_name': 'ORION HEXA SILVER 19.8*22. SPAIN 355',
            'quantity': -4.0,
            'product_cost': 0.58,
            'price_unit': 1.25,
            'remaining_qty': 129.0,
            'seller_name': 'السيد برغش المطيري المحترم ',
            'jour': 'Cash,'
        },
        2897: {
            'order_date': datetime.datetime(2021, 7, 23, 20, 4, 2, 939000),
            'product_id': 2897,
            'product_name': 'BLANCO BR RECT LA 30*60 SPAIN 456',
            'quantity': -6.0,
            'product_cost': 3.5,
            'price_unit': 4.0,
            'remaining_qty': 6.0,
            'seller_name': 'السيد احمد منصور العازمي',
            'jour': 'Cash,'
        },
        2828: {
            'order_date': datetime.datetime(2021, 7, 23, 20, 8, 38, 380000),
            'product_id': 2828,
            'product_name': 'كاونتر مدور رمادي فاتح 1277 (36*12 CM',
            'quantity': -1.0,
            'product_cost': 0.0,
            'price_unit': 27.5,
            'remaining_qty': -1.0,
            'seller_name': 'السيد علي المطيري المحترم',
            'jour': 'Cash,'
        },
        3041: {
            'order_date': datetime.datetime(2021, 7, 23, 20, 7, 11, 189000),
            'product_id': 3041,
            'product_name': 'PRIS TINENZA 30*60 SPAIN',
            'quantity': -2.0,
            'product_cost': 5.0,
            'price_unit': 6.5,
            'remaining_qty': -13.0,
            'seller_name': 'السيد محمد حسن الكندري المحترم',
            'jour': 'Cash,'
        },
    }
    
    # .items() is a tuple of (key, value), where key (accessed via [0]) is an int e.g. 2897 and value (accessed via [1]) is a dict e.g. {'order_date': datetime.datetime(2021, 7, 23, 20, 4, 2, 939000), 'product_id': 2897, 'product_name': 'BLANCO BR RECT...}
    products_sold = dict(
        sorted(
            products_sold.items(), key=lambda item: item[1]['order_date']
        )
    )
    
    print("Whole dict")
    print(products_sold)
    
    print("\n==========\n")
    
    print("Dict items")
    for key, value in products_sold.items():
        print(key, value)
    

    Output:

    Whole dict
    {2897: {'order_date': datetime.datetime(2021, 7, 23, 20, 4, 2, 939000), 'product_id': 2897, 'product_name': 'BLANCO BR RECT LA 30*60 SPAIN 456', 'quantity': -6.0, 'product_cost': 3.5, 'price_unit': 4.0, 'remaining_qty': 6.0, 'seller_name': 'السيد احمد منصور العازمي', 'jour': 'Cash,'}, 3041: {'order_date': datetime.datetime(2021, 7, 23, 20, 7, 11, 189000), 'product_id': 3041, 'product_name': 'PRIS TINENZA 30*60 SPAIN', 'quantity': -2.0, 'product_cost': 5.0, 'price_unit': 6.5, 'remaining_qty': -13.0, 'seller_name': 'السيد محمد حسن الكندري المحترم', 'jour': 'Cash,'}, 2828: {'order_date': datetime.datetime(2021, 7, 23, 20, 8, 38, 380000), 'product_id': 2828, 'product_name': 'كاونتر مدور رمادي فاتح 1277 (36*12 CM', 'quantity': -1.0, 'product_cost': 0.0, 'price_unit': 27.5, 'remaining_qty': -1.0, 'seller_name': 'السيد علي المطيري المحترم', 'jour': 'Cash,'}, 2412: {'order_date': datetime.datetime(2021, 7, 26, 13, 59, 33, 351000), 'product_id': 2412, 'product_name': 'ORION HEXA SILVER 19.8*22. SPAIN 355', 'quantity': -4.0, 'product_cost': 0.58, 'price_unit': 1.25, 'remaining_qty': 129.0, 'seller_name': 'السيد برغش المطيري المحترم ', 'jour': 'Cash,'}, 2516: {'order_date': datetime.datetime(2021, 7, 26, 16, 10, 10, 461000), 'product_id': 2516, 'product_name': 'TRENTO GRIS 30*60 NEW TILE SPAIN 514', 'quantity': -1.0, 'product_cost': 4.0, 'price_unit': 5.5, 'remaining_qty': -23.0, 'seller_name': 'السيد ابو فهد', 'jour': 'Cash,'}}
    
    ==========
    
    Dict items
    2897 {'order_date': datetime.datetime(2021, 7, 23, 20, 4, 2, 939000), 'product_id': 2897, 'product_name': 'BLANCO BR RECT LA 30*60 SPAIN 456', 'quantity': -6.0, 'product_cost': 3.5, 'price_unit': 4.0, 'remaining_qty': 6.0, 'seller_name': 'السيد احمد منصور العازمي', 'jour': 'Cash,'}
    3041 {'order_date': datetime.datetime(2021, 7, 23, 20, 7, 11, 189000), 'product_id': 3041, 'product_name': 'PRIS TINENZA 30*60 SPAIN', 'quantity': -2.0, 'product_cost': 5.0, 'price_unit': 6.5, 'remaining_qty': -13.0, 'seller_name': 'السيد محمد حسن الكندري المحترم', 'jour': 'Cash,'}
    2828 {'order_date': datetime.datetime(2021, 7, 23, 20, 8, 38, 380000), 'product_id': 2828, 'product_name': 'كاونتر مدور رمادي فاتح 1277 (36*12 CM', 'quantity': -1.0, 'product_cost': 0.0, 'price_unit': 27.5, 'remaining_qty': -1.0, 'seller_name': 'السيد علي المطيري المحترم', 'jour': 'Cash,'}
    2412 {'order_date': datetime.datetime(2021, 7, 26, 13, 59, 33, 351000), 'product_id': 2412, 'product_name': 'ORION HEXA SILVER 19.8*22. SPAIN 355', 'quantity': -4.0, 'product_cost': 0.58, 'price_unit': 1.25, 'remaining_qty': 129.0, 'seller_name': 'السيد برغش المطيري المحترم ', 'jour': 'Cash,'}
    2516 {'order_date': datetime.datetime(2021, 7, 26, 16, 10, 10, 461000), 'product_id': 2516, 'product_name': 'TRENTO GRIS 30*60 NEW TILE SPAIN 514', 'quantity': -1.0, 'product_cost': 4.0, 'price_unit': 5.5, 'remaining_qty': -23.0, 'seller_name': 'السيد ابو فهد', 'jour': 'Cash,'}
    

    Sample run:

    This assumes that you are using Python 3.7 or later, as documented since only from that version are dictionaries ordered. Otherwise, use a list (or collections.OrderedDict), so change above to list(sorted(....

    Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.