xlrtx xlrtx - 4 months ago 6
Python Question

Python, how to move dict under itself with a new attribute? Eg dict['key'] = dict

I have an array of very large dictionaries, and need to put each dict itself under a new key.

I know

dict['key'] = dict
won't work and will result a recursive dict in python. Currently, I'm doing something like:

new_dict['key'] = old_dict


and it will waste memory, is there a better way doing it?

Answer

Adding a small bit to mgilson's answer:

new_dict['key'] = old_dict

will not be a waste of memory. This assignment operator only assigns a reference to old_dict. Elements from old_dict aren't copied.

But regardless of how you do it - directly or via a different variable name, you'll get circular reference, which is valid for some usages and not valid for some other.

Comments