在 MATLAB 中使用 Python 字典
您可以将 Python® 字典 (dict) 转换为 MATLAB 字典或结构体,并将 MATLAB 字典或结构体转换为 Python dict。
您可以使用
dictionary函数将 Python 字典转换为 MATLAB 字典。您也可以使用struct函数将 Python 字典转换为 MATLAB 结构体。您可以使用
py.dict函数将 MATLAB 字典或结构体转换为 Python 字典。您还可以将 MATLAB 字典直接传递给 Python 函数,而无需先将其转换为 Python 字典。
将 Python 字典转换为 MATLAB 字典或结构体
如果您有 Python 字典,您可以使用 dictionary 函数将其转换为 MATLAB 字典。(自 R2024a 起)
例如,创建一个 Python 字典并将其转换为 MATLAB 字典。在这种情况下,MATLAB 将键转换为字符串,将值转换为双精度值。
dp = py.dict(soup=3.57,bread=2.29,bacon=3.91,salad=5.00); dm = dictionary(dp)
dm =
dictionary (string ⟼ double) with 4 entries:
"soup" ⟼ 3.5700
"bread" ⟼ 2.2900
"bacon" ⟼ 3.9100
"salad" ⟼ 5
MATLAB 尽可能将 Python 键和值转换为 MATLAB 中的等效类型。如果 Python 字典的键在自动转换为 MATLAB 数据类型时不属于同一数据类型,则这些键包装在元胞数组中。Python 字典值也是如此。
或者,只要 Python 字典键是有效的 MATLAB 标识符,就可以使用结构体函数将 Python 字典转换为 MATLAB 结构体。
sm = struct(dp)
sm = struct with fields:
soup: 3.5700
bread: 2.2900
bacon: 3.9100
salad: 5
将 MATLAB 字典转换为 Python 字典
MATLAB 将传递给 Python 函数的任何 MATLAB 字典隐式转换为 Python 字典。但是,如果您有 MATLAB 字典,也可以使用 py.dict 将其显式转换为 Python 字典。Python 字典的键和值由 MATLAB 类型的默认转换规则确定,这些规则在从 MATLAB 在 MATLAB 与 Python 之间传递数据 中进行描述。
例如,创建一个 MATLAB 字典并将其直接传递给 Python 函数 py.len,而无需先将其转换为 Python 字典。
dm = dictionary(["Robert" "Mary" "Jack"],[357 229 391]); l = py.len(dm)
l =
Python int with properties:
denominator: [1×1 py.int]
imag: [1×1 py.int]
numerator: [1×1 py.int]
real: [1×1 py.int]
3
您还可以使用 py.dict 将 MATLAB 字典转换为 Python 字典。
dp = py.dict(dm)
dp =
Python dict with no properties.
{'Robert': 357.0, 'Mary': 229.0, 'Jack': 391.0}
在 MATLAB 中使用 Python 字典方法
您可以在 MATLAB 中使用 Python 字典方法,方法是将该方法作为函数调用并将 Python 字典作为第一个参量传递。
例如,使用 update 方法更改 Python 字典中的键和值。首先,创建一个 Python 字典,其中包含患者和测试结果。然后,更新 test1 的结果。
patientp = py.dict(name="John Doe", ... test1 = [], ... test2 = [220.0, 210.0, 205.0], ... test3 = [180.0, 178.0, 177.5]); new_test1 = py.dict(test1=[79.0, 75.0, 73.0]); % This call is equivalent to the Python command patient.update(new_test1) update(patientp,new_test1);
您可以组合使用 Python 字典和 MATLAB 字典来显示输出。
patientm = dictionary(patientp); x = sprintf("%s's test1 results: %d %d %d", ... string(patientp{"name"}), double(patientm{"test1"})); disp(x)
John Doe's test1 results: 79 75 73