Python, how to move dict under itself with a new attribute? Eg dict['key'] = dict
Question: 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: A `dict` _can_ hold a reference to itself:

    
    
    >>> d = {'foo': 'bar'}
    >>> d['self'] = d
    >>> d
    {'self': {...}, 'foo': 'bar'}
    >>> d['self']['self']['self']['self']['foo']
    'bar'
    

Of course, there are _some_ things that you can't do (e.g. dump it to `json`):

    
    
    >>> import json
    >>> json.dumps(d)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 243, in dumps
        return _default_encoder.encode(obj)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode
        chunks = self.iterencode(o, _one_shot=True)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode
        return _iterencode(o, 0)
    ValueError: Circular reference detected
    

If you actually need to persist this in some way, then you probably don't have
another option other than to copy it when you add it to itself:

    
    
    d = {'foo': 'bar'}
    d['self'] = d.copy()
    

Or writing some sort of custom logic so that when deserializing, you replace
certain sentinel values with the `dict` itself (which may or may not work
depending on why you need this particular feature)

