How do I convert a Python dictionary to a MATLAB type?
21 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
MathWorks Support Team
am 8 Mai 2020
Bearbeitet: MathWorks Support Team
am 3 Feb. 2025
I have a Python dictionary in MATLAB which I would like to convert to a MATLAB type, but I am having trouble with the method used in this document page:
- https://www.mathworks.com/help/releases/R2020a/matlab/matlab_external/use-python-dict-type-in-matlab.html
I believe the problem is converting to a MATLAB "struct." The data in my dictionary does not conform to struct naming conventions listed here:
- https://www.mathworks.com/help/releases/R2020a/matlab/ref/struct.html#d120e1193691
Akzeptierte Antwort
MathWorks Support Team
am 17 Jan. 2025
Bearbeitet: MathWorks Support Team
am 3 Feb. 2025
While MATLAB structs have strict naming conventions for their data, there are other MATLAB data types which a dictionary can be converted into.
If we already have our Python environment loaded (which can be done manually with the MATLAB "pyenv" function), we can create a Python dictionary directly in MATLAB with the following command:
dict = py.dict(pyargs('2020-1-1 10:00:00.1', 'Value_1', '2020-1-2 12:10:00.5', 'Value_2'))
We can now convert this Python dictionary into a MATLAB map by iterating over the dictionary:
M = containers.Map; for raw_key = py.list(keys(dict)) key = raw_key{1}; value = dict{key}; M(string(key)) = string(value); end
Alternatively, we can convert the dictionary into a MATLAB table:
T = table; for raw_key = py.list(keys(dict)) key = raw_key{1}; value = dict{key}; T2 = table(string(value), 'VariableNames', [string(key)]); T = [T T2]; end
Note that this dictionary could not be converted into a MATLAB struct because the keys of the dictionary do not conform to struct naming conventions, since they do not start with a letter.
For more detailed information or guidance on the current release, please visit the following link:
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Call Python from MATLAB finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!