Skip to content
Advertisement

Unexpected UserDict Behavior

I am working on a project and need to make use of UserDict instead of dict. I am importing a JSON file that is a dictionary with lists containing more dictionaries.

Here is some example code and the behavior differences I am seeing:

JavaScript

The output:

JavaScript

Why did the new key not get added to person_user_dict and how can I get UserDict to behave the same way as a dictionary?

Advertisement

Answer

Because you created a new dictionary here:

JavaScript

This isn’t unexpected at all, indeed, this is how dict works. You would see the same exact behavior if you did:

JavaScript

You would need to recursively convert all the dict’s to UserDict objects instead. But actually, you just want to use the object_pairs_hook for the json decoder:

JavaScript
Advertisement