Use Pythondict
Variables in MATLAB
This example shows how to use Python® dictionary (dict
) variables in MATLAB®.
To call a Python function that takes adict
输入参数,创建apy.dict
variable. To convert adict
to a MATLAB variable, call thestruct
function.
Create Pythondict
Variable
创建一个dict
variable to pass to a Python function. Thepyargs
function creates keyword arguments.
studentID = py.dict(pyargs('Robert',357,'Mary',229,'Jack',391))
studentID = Python dict with no properties. {'Robert': 357.0, 'Mary': 229.0, 'Jack': 391.0}
Alternatively, create a MATLAB structure and convert it to adict
variable.
S = struct('Robert',357,'Mary',229,'Jack',391); studentID = py.dict(S)
studentID = Python dict with no properties. {'Robert': 357.0, 'Mary': 229.0, 'Jack': 391.0}
Use Pythondict
Type in MATLAB
To convert adict
type returned from a Python function to a MATLAB variable, callstruct
.
Suppose you have a Python function that returns menu items and prices in adict
object namedorder
. To run this code in MATLAB, create this variable.
order = py.dict(pyargs('soup',3.57,'bread',2.29,'bacon',3.91,'salad',5.00))
order = Python dict with no properties. {'soup': 3.57, 'bread': 2.29, 'bacon': 3.91, 'salad': 5.0}
Convertorder
to a MATLAB variable.
myOrder = struct(order)
myOrder =struct with fields:soup: 3.5700 bread: 2.2900 bacon: 3.9100 salad: 5
Display the price of bacon using MATLAB syntax.
price = myOrder.bacon
price = 3.9100
Display the price of bacon using Python syntax. The type of variableprice
is double, which you can use in MATLAB.
price = order{'bacon'}
price = 3.9100
A dictionary has pairs of keys and values. Display the menu items in the variableorder
using the Pythonkeys
function.
keys(order)
ans = Python dict_keys with no properties. dict_keys(['soup', 'bread', 'bacon', 'salad'])
Display all prices using the Pythonvalues
function.
values(order)
ans = Python dict_values with no properties. dict_values([3.57, 2.29, 3.91, 5.0])
Passdict
Argument to Python Method
The Pythondict
class has anupdate
method. To run this code, create adict
variable of patients and test results.
patient = py.dict(pyargs('name','John Doe',...'test1', [],...'test2', [220.0, 210.0, 205.0],...'test3', [180.0, 178.0, 177.5]));
Convert the patient name to a MATLAB string.
string(patient{'name'})
ans = "John Doe"
Update and display the results fortest1
using theupdate
method.
update(patient,py.dict(pyargs('test1',[79.0, 75.0, 73.0]))) P = struct(patient); disp([“test1结果”+string(patient{'name'})+": "+num2str(double(P.test1))])
test1 results for John Doe: 79 75 73