I have a big nested dict nested_dict
which was created using parallel processing, resulting in DictProxy objects at each level. To avoid having to re-run the creation of this dict which takes hours I want to save everything in a JSON file. As per How to convert a DictProxy object into JSON serializable dict? it is possible to convert a DictProxy object to a dict, and then make it JSON. But since I have DictProxy objects nested, running json.dumps(nested_dict.copy())
returns TypeError: Object of type DictProxy is not JSON serializable
.
Is there an efficient way to recursively convert all DictProxy objects to dict to allow saving in a JSON file?
2
Answers
Simply creating a new empty dict and populating it using for loops over the keys until the most inner dict solved it:
And then
Maybe it isn't the most effective, but it works!
How about some dict comprehension and a little recursion here:
Output
As a bonus, this would even work if there were no
DictProxy
objects or the dictionary wasn’t nested