在日期时间字段中对字典进行排序

时间:2021-07-29 05:24:16

标签: python odoo-12

你好,我有一个代码可以让我输入 dict 这里是 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,'}}

我尝试过列表理解,例如:

                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']

但每次我尝试这个我都会收到一个错误 "ValueError: too many values to unpack (expected 2)"

我什至尝试过:

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

并通过它作为回报仍然出现错误

如何对上面的字典进行排序我不知道会有什么帮助将不胜感激,下面是我希望字典按 "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}

1 个答案:

答案 0 :(得分:0)

这个说法是错误的:

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

您正在迭代 products_sold.get(line.product_id.id) 的值并期望每个项目包含 5 个变量的序列。 products_sold.get(line.product_id.id) 的值是一个字典:

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

输出:

<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,'}

这意味着迭代 products_sold.get(line.product_id.id) 相当于迭代键 products_sold.get(line.product_id.id).keys(),它们只是字符串:

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

输出:

<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

所以你想要做的是将每个字符串分配给这 5 个变量:

(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 ...

显然,它们不适合,这就是您遇到错误 ValueError: too many values to unpack (expected 2) 的原因。

解决方案

以下是根据 products_sold 属性对所有 order_date 进行排序的方法。

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)

输出:

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,'}

样品运行:

这假设您使用的是 Python 3.7 或更高版本,如 documented,因为只有从该版本开始才对字典进行排序。否则,请使用列表(或 collections.OrderedDict),因此将上面更改为 list(sorted(...

<块引用>

3.7 版更改:字典顺序保证插入 命令。此行为是 CPython 3.6 的实现细节。