Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a python dictionary object in MATLAB?

Tags:

python

matlab

I'm playing with the new capability in MATLAB 2014b where you can call python directly from matlab and get python objects in the workspace (like you've been able to with Java for a long time). I have successfully called a function and gotten a dictionary into the workspace, but I'm stuck on how to harvest the values from it. In this case I have a dictionary full of dictionaries, so I can't just convert it to MATLAB cells like they do in their example.

So a specific question: if I have a dictionary in MATLAB called "A", how to I get the sub-dictionary A['2'] out?

like image 633
Mastiff Avatar asked Oct 19 '22 18:10

Mastiff


1 Answers

By consulting the MATLAB External Interfaces documentation, the Python dict type is essentially the same interface as a containers.Map. You need to use the values function to extract the value that you want for a certain key. As such, you would call values like so, given that your Python dictionary is stored in A and you want to use '2' as the key to index into your dictionary:

val = values(A, '2');

As such, val would contain what the associated value is with the key of '2'. MATLAB also has the ability to use multiple keys and it would return multiple values - one per key. Therefore, you could also do something like this:

val = cell(values(A, {'1', '2', '3'}));

val would be a three element cell array, where each element is the value for the associated keys that you input in. It is imperative that you convert the output of values into a cell array, because this would normally be a list in Python. In order to use these results in MATLAB, we need to convert to a cell.

Therefore, val{1} would be the dictionary output when you used '1' as the key. Similarly, val{2} would be the dictionary output when you used '2' as the key and so on.


Here are some more operations on a containers.Map object for you. If you want all of the keys in a dictionary, use the keys function:

k = keys(A);

If you were to just use values with the dictionary by itself, like so:

val = cell(values(A));

It would produce all values for every key that exists in your dictionary stored into a cell array.

If you wanted to update a particular key in your Python dictionary, use the update function:

update(A,py.dict(pyargs('4',5.677)));

Here, we use the dictionary A, and update the key-value pair, where the key is '4' and the new value is 5.677.

like image 143
rayryeng Avatar answered Oct 22 '22 07:10

rayryeng