Matlab structure in Python [duplicate]

2019-06-13 07:05发布

问题:

This question already has an answer here:

  • Matlab struct array to python 1 answer

Is there any variable in python similar to Matlab structures?

I would like to create a structure within another structure as in Matlab, but in Python. I've looking into Python Dictionaries, but I have not find an easy way to access to its values. Which in Matlab is really easy.

In Matlab I would do the following:

Create the structure

structure.parent1.variable1 = 23;
structure.parent1.variable2 = 19;
structure.parent1.variable3 = 19;
structure.parent2.variable1 = 10;
structure.parent2.variable2 = 11;

structure = 

    parent1: [1x1 struct]
    parent2: [1x1 struct]

And then access to the variable simply tipying

structure.parent2.variable1

ans =

    10

回答1:

what is wrong with dictionaries in python - to create and then access them :

structure = {}
structure["parent1"] = {}
structure["parent1"]["variable1"] = 23;
structure["parent1"]["variable2"] = 19;
structure["parent1"]["variable3"] = 19;
structure["parent2"] = {}
structure["parent2"]["variable1"] = 10;
structure["parent2"]["variable2"] = 11;


回答2:

Using a dictionary you can access elements like this

structure['parent2']['variable1']