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?
The key difference is how you can access within them. Both arrays and dictionaries are containers and can be read sequentally (e.g. arrays can be enumerated by means of an index and dictionaries by means of a key). But while arrays maintain the order amongs objects, dictionaries not.
There are no dictionaries in php, but PHP array's can behave similarly to dictionaries in other languages because they have both an index and a key (in contrast to Dictionaries in other languages, which only have keys and no index).
A dictionary is very similar to an array. Whereas an array maps the index to the value, a dictionary maps the key to the value.
A dictionary is sometimes called an associative array because it associates a key with an item. The keys behave in a way similar to indices in an array, except that array indices are numeric and keys are arbitrary strings. Each key in a single Dictionary object must be unique.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With