Python – array in php and dict in python are the same

arraysPHPpython

I have a project using python and i want to convert the php to python. I have confused in the array of php in converting it to python…

in the old code of the php… it looks like this,

array(
      "Code"          => 122,
      "Reference"     => 1311,
      "Type"          => 'NT',
      "Amount"        => 100.00
);

and this is what i did in converting it to python …

dict = {
          "Code":122,
          "Reference":1311,
          "Type":'NT',
          "Amount":100.00
}

is my converting php to python is correct?

Best Answer

Your conversion is essentially correct (though I wouldn't use dict as a variable name since that masks a built-in class constructor of the same name). That being said, PHP arrays are ordered mappings, so you should use a Python OrderedDict instead of a regular dict so that the order of insertion gets preserved:

>>> import collections
>>> od = collections.OrderedDict([
        ('Code', 122),
        ('Reference', 1311),
        ('Type', 'NT'),
        ('Amount', 100.00),
])

>>> print od['Amount']
100.0

>>> od.keys()
['Code', 'Reference', 'Type', 'Amount']