数组中的PHP和字典在Python是一样的吗? [英] array in php and dict in python are the same?

查看:1233
本文介绍了数组中的PHP和字典在Python是一样的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有使用Python项目,我想在PHP转换为蟒蛇。我混淆了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...

在PHP的老code ......它看起来像这样,

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
}

是我转换PHP到Python是正确的?

is my converting php to python is correct?

推荐答案

您转换基本上是正确的(虽然我不会用的字典的作为变量名,因为这掩盖了内置类的构造函数同名)。话虽这么说, PHP数组是的有序映射的,所以你应该使用 Python的OrderedDict 的,而不是一个普通字典,以便插入的顺序获得preserved

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

这篇关于数组中的PHP和字典在Python是一样的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆