Thursday, 4 March 2021

Deep copying a Python dict in Matlab

Matlab as of (R2020a) Update 4 (Ver: 9.8.0.1417392) doesn't support deep copying of Python dict objects. If a user is not careful, the assignment of a dict object (say, D) to a variable (say, X) and then modifying X, will change the original dict object, D.

copy() provided in Matlab for py.dict class of objects creates a shallow copy.

 As I needed a copy of object which is created anew and doesn't change original object, I wrote a recursive function that assigns a dict for every level of the input dict object.

The implementation is given below. Please let me know if you find any edge cases or bugs.


No comments:

Post a Comment