gadss gadss - 2 months ago 6
Python Question

array in php and dict in python are the same?

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,

"Code" => 122,
"Reference" => 1311,
"Type" => 'NT',
"Amount" => 100.00

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

dict = {

is my converting php to python is correct?


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

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