gpt4 book ai didi

php - php 中的数组和 python 中的 dict 是一样的吗?

转载 作者:太空狗 更新时间:2023-10-29 21:32:26 25 4
gpt4 key购买 nike

我有一个使用 python 的项目,我想将 php 转换为 python。我在将 php 数组转换为 python 时感到困惑...

在 php 的旧代码中......它看起来像这样,

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

这就是我在将它转换为 python 时所做的......

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

我将 php 转换为 python 是否正确?

最佳答案

您的转换基本上是正确的(尽管我不会使用 dict 作为变量名,因为它掩盖了同名的内置类构造函数)。也就是说,PHP arrays有序映射,所以你应该使用 Python OrderedDict而不是常规字典,以便保留插入顺序:

>>> 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 - php 中的数组和 python 中的 dict 是一样的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8981282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com