Main Content

Use Python dict Variables in MATLAB

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

To call a Python function that takes a dict input argument, create a py.dict variable. To convert a dict to a MATLAB variable, call the struct function.

Create Python dict Variable

Create a dict variable to pass to a Python function. The pyargs 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 a dict 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 Python dict Type in MATLAB

To convert a dict type returned from a Python function to a MATLAB variable, call struct.

Suppose you have a Python function that returns menu items and prices in a dict object named order. 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}

Convert order 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 variable price 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 variable order using the Python keys function.

keys(order)
ans = 
  Python dict_keys with no properties.

    dict_keys(['soup', 'bread', 'bacon', 'salad'])

Display all prices using the Python values function.

values(order)
ans = 
  Python dict_values with no properties.

    dict_values([3.57, 2.29, 3.91, 5.0])

Pass dict Argument to Python Method

The Python dict class has an update method. To run this code, create a dict 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 for test1 using the update method.

update(patient,py.dict(pyargs('test1',[79.0, 75.0, 73.0])))
P = struct(patient);
disp(['test1 results for '+string(patient{'name'})+": "+num2str(double(P.test1))])
test1 results for John Doe: 79  75  73