简体   繁体   中英

Python: Append Dictionary new element

Convert PHP code:

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

To python:

self.plane = {};

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

Does not work.

1) self.plane[slice_id][f] -> not yet initialized. Only create this element if necessary.

2) [] -> push element to array

3) Python dictionary are not usually multi-dimensional

Try like this

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

The method append() appends a passed obj into the existing list.

self.plane[slice_id][f][] = {'x' : y, 'y' : z}; is not valid syntax for the python

Demo

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM