MATLAB Answers

# Transform a Dict (or any python data structure) to Struct or Cell Array in Matlab.

104 views (last 30 days)
Ajpaezm on 8 Dec 2017
Answered: Ajpaezm on 18 Dec 2017
Hi,
I'd like to create a structure or a cell array from Matlab given a Python dictionary. I'm using the built-in Python API to call from Matlab a user-defined function I wrote in Python.
The function I wrote (saved in a file called 'py2mat.py') is like this:
def test(w,j,l):
array1 = np.array([w,j,l])
array2 = np.array(['a','b','c'])
array3 = np.array([1.01,2.02,3.03])
df = pd.DataFrame({'array1':array1, 'array2':array2,'array3':array3})
return df.to_dict()
To call in Matlab, I do this:
N=py.py2mat.test(2,4,5);
s=struct(N);
And everything's great, but... when I look into the struct, all I got is this data structure with nested dictionaries. So, how do I do to display the values of the dictionaries into struct fields or cell arrays for further manipulation?
I'd like to know.
Thanks a lot for your time!
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Accepted Answer

Ajpaezm on 18 Dec 2017
I wrote a small function that transforms the dictionary into a cell array and then that cell array is used to populate a structure. Same principle can be applied to other python dictionaries. Hope this somehow works for anyone else working with Matlab and Python.
function new_s=my_py2mat(a,b,c)
n=py.py2mat.test(a,b,c);
s=struct(n);
field_list=fieldnames(s);
rows=double(py.len(s.(field_list{1}))); %size and numel can't acquire the dimension of a python dictionary, that's why we call py.len()
new_array=cell(rows,numel(field_list));
for i=1:numel(field_list)
temp=s.(field_list{i});
for j=1:rows
if isa(temp{j-1},'py.str')
new_array{j,i}=char(temp{j-1});
elseif isa(temp{j-1},'py.int')
new_array{j,i}=double(temp{j-1});
else
new_array{j,i}=temp{j-1};
end
end
s.(field_list{i})=new_array(:,i);
end
new_s=s;
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!