Python:追加字典新元素

时间:2014-12-06 20:06:26

标签: python arrays dictionary multidimensional-array

转换PHP代码:

$this->plane[$slice_id][$f][] = array('x' => $y, 'y' => $z);

to python:

self.plane = {};

self.plane[slice_id][f][] = {'x' : y, 'y' : z};

不起作用。

1)self.plane[slice_id][f] - >尚未初始化。只在必要时才创建此元素。

2)[] - >将元素推送到数组

3)Python字典通常不是多维的

1 个答案:

答案 0 :(得分:0)

试试这个

self.plane[slice_id][f] = [] 
self.plane[slice_id][f].append( {'x' : y, 'y' : z} )

方法append()将传递的obj附加到现有列表中。

self.plane[slice_id][f][] = {'x' : y, 'y' : z};不是python的有效语法

<强>演示

>>> new_list = []
>>> new_list[] = 'test'
  File "<stdin>", line 1
    new_list[] = 'test'
             ^
SyntaxError: invalid syntax