MATLAB での Python ディクショナリの使用
Python® ディクショナリ (dict
) から MATLAB のディクショナリまたは構造体への変換、あるいはその逆の変換が可能です。
関数
dictionary
を使用して Python ディクショナリを MATLAB ディクショナリに変換できます。あるいは、関数struct
を使用して Python ディクショナリを MATLAB 構造体に変換できます。関数
py.dict
を使用して MATLAB のディクショナリまたは構造体を Python ディクショナリに変換できます。MATLAB ディクショナリは、先に Python ディクショナリに変換せずに Python 関数に直接渡すこともできます。
Python ディクショナリから MATLAB のディクショナリまたは構造体への変換
Python ディクショナリがある場合、関数 dictionary
を使用して MATLAB ディクショナリに変換できます。(R2024a 以降)
たとえば、Python ディクショナリを作成し、それを MATLAB ディクショナリに変換します。この場合、MATLAB はキーを string に変換し、値を double に変換します。
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 の型に変換します。MATLAB データ型に自動で変換するときに、Python ディクショナリのキーがすべて同じデータ型でない場合は、キーが cell 配列にラップされます。Python ディクショナリの値についても同様です。
Python ディクショナリのキーが有効な MATLAB 識別子である場合は、代わりに関数 struct を使用して 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 ディクショナリのキーと値は、Python への MATLAB データの引き渡しで説明されている MATLAB 型の既定の変換ルールによって決定されます。
たとえば、MATLAB ディクショナリを作成し、それを Python ディクショナリに先に変換せずに Python 関数 py.len
に直接渡します。
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 ディクショナリのメソッドの使用
Python ディクショナリのメソッドを MATLAB で使用するには、そのメソッドを関数として呼び出し、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")}(1)), ... double(patientm{("test1")}(2)), double(patientm{("test1")}(3))); disp(x)
John Doe's test1 results: 79 75 73