Search code examples
python-2.7dictionaryopenerp-7odoo-8

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


I am using python 2.7.X version and I need to display my result of list of dictionary in key order same as in my output.

CREATE THE LIST OF DICTIONARY :

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

RESULT :

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

Here you can easily see my order of keys is different than the order of keys in my result.

My question is that I need to displaying the same order of keys which I have in my list of dictionary keys in my output.

How can I set the same order of list of keys to be in my result ?


Solution

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