0

我正在使用 python 2.7.X 版本,我需要以与输出相同的键顺序显示字典列表的结果。

创建字典列表:

for acc_data in acc_pool.browse(cr,uid,acc_ids_in):
    for line in acc_data.invoice_line:
        c+=1
        lst_data2.append({
            'SupplierName':acc_data.partner_id.name or '',
            'SupplierBRN':acc_data.partner_id.com_reg_no1 or '',
            'InvoiceDate':acc_data.date_invoice or '',
            'InvoiceNumber':acc_data.number or '',
            'ImportDeclarationNo':'',
            'LineNumber':c,
            'ProductDescription':line.product_id.name or '',
            'PurchaseValueMYR':line.price_unit or 0.00,
            'GSTValueMYR':'',
            'TaxCode':line.invoice_line_tax_id.name or '',
            'FCYCode':'',
            'PurchaseFCY':'',
            'GSTFCY':'',
            })

结果 :

> lst_data2 [{'ProductDescription': u'Ink Cartridge', 'SupplierBRN': '', 'ImportDeclarationNo': '', 'GSTValueMYR': '', 'SupplierName': u'Vicking Direct', 'GSTFCY': '', 'TaxCode': u'Purchase Tax 15.00%', 'InvoiceDate': '2015-03-24', 'FCYCode': '', 'PurchaseFCY': '', 'PurchaseValueMYR': 58.0, 'LineNumber': 1, 'InvoiceNumber': u'EXJ/2015/002'}, {'ProductDescription': u'Toner Cartridge', 'SupplierBRN': '', 'ImportDeclarationNo': '', 'GSTValueMYR': '', 'SupplierName': u'Vicking Direct', 'GSTFCY': '', 'TaxCode': u'OTAX X', 'InvoiceDate': '2015-03-24', 'FCYCode': '', 'PurchaseFCY': '', 'PurchaseValueMYR': 65.0, 'LineNumber': 2, 'InvoiceNumber': u'EXJ/2015/002'}]

在这里,您可以轻松地看到我的键顺序与我的结果中的键顺序不同。

我的问题是我需要在输出的字典键列表中显示相同的键顺序。

如何在结果中设置相同顺序的键列表?

4

2 回答 2

1

dict does not remember order. ordereddict does; use that.

Unfortunately, you can't use the dict literal, because as soon as you do, you lose ordering. You can use this syntax:

from collections import OrderedDict
o = OrderedDict([("a", 1), ("b", 2)])
# `a` is first; `b` is second.
于 2015-03-27T06:28:47.380 回答
0

我已经解决了我发布的问题。

只是我们需要将python库添加到我们的文件中并按如下方式使用它。

from collections import OrderedDict

    for acc_data in acc_pool.browse(cr,uid,acc_ids_in):
        c=0
        for line in acc_data.invoice_line:
            if line.invoice_line_tax_id:
                c+=1
                lst_data2.append(OrderedDict([
                    ('SupplierName',acc_data.partner_id.name or ''),
                    ('SupplierBRN',acc_data.partner_id.com_reg_no or ''),
                    ('InoiveDate',acc_data.date_invoice or ''),
                    ('InvoiceNumber',acc_data.number or ''),
                    ('ImportDeclarationNo',''),
                    ('LineNumber',c),
                    ('ProductDescription',line.product_id.name or ''),
                    ('PurchaseValueMYR',line.price_unit or 0.00),
                    ('GSTValueMYR',''),
                    ('TaxCode',line.invoice_line_tax_id.name or ''),
                    ('FCYCode',''),
                    ('PurchaseFCY',''),
                    ('GSTFCY',''),
                    ]))

我希望这对某人有所帮助。:)

于 2015-04-17T07:15:20.897 回答