Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array in php and dict in python are the same?

Tags:

python

arrays

php

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?

like image 569
gadss Avatar asked Jan 24 '12 02:01

gadss


People also ask

Is an array the same as a dictionary in Python?

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.

Are PHP arrays dictionaries?

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

Are dictionaries like arrays?

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.

Are dictionaries an array?

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.


1 Answers

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']
like image 151
Raymond Hettinger Avatar answered Sep 22 '22 13:09

Raymond Hettinger