在我的输出中显示与我在字典键列表中相同的键顺序

Displaying the same order of keys which I have in my list of dictionary keys in my output

我正在使用 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'}]

在这里您可以很容易地看到我的键顺序与结果中的键顺序不同。

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

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

dict不记得顺序了。 ordereddict 确实如此;用那个。

不幸的是,您不能使用 dict 文字,因为一旦这样做,您就会失去排序。您可以使用以下语法:

from collections import OrderedDict
o = OrderedDict([("a", 1), ("b", 2)])
# `a` is first; `b` is second.

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

只是我们需要添加 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',''),
                    ]))

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