Main Content

Use PythondictVariables in MATLAB

This example shows how to use Python® dictionary (dict) variables in MATLAB®.

To call a Python function that takes adict输入参数,创建apy.dictvariable. To convert adictto a MATLAB variable, call thestructfunction.

Create PythondictVariable

创建一个dictvariable to pass to a Python function. Thepyargsfunction 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 adictvariable.

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 PythondictType in MATLAB

To convert adicttype returned from a Python function to a MATLAB variable, callstruct.

Suppose you have a Python function that returns menu items and prices in adictobject 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}

Convertorderto 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 variablepriceis 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 variableorderusing the Pythonkeysfunction.

keys(order)
ans = Python dict_keys with no properties. dict_keys(['soup', 'bread', 'bacon', 'salad'])

Display all prices using the Pythonvaluesfunction.

values(order)
ans = Python dict_values with no properties. dict_values([3.57, 2.29, 3.91, 5.0])

PassdictArgument to Python Method

The Pythondictclass has anupdatemethod. To run this code, create adictvariable 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 fortest1using theupdatemethod.

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