Strange behaviour of delete dictionary operation on nested dictionary
<pre><code>#!/usr/bin/python
import numpy as np

td={}
d = {}
for col in ['foo','bar','baz']:
    for row in ['a','b','c','d']:
        td.setdefault(row, np.random.randn())
        d.setdefault(col, td)

print d
del d['foo']['c']
print d
</code></pre>

<p>output:</p>

<pre><code>{'baz': {'a': -1.6340274257732716, 'c': 0.6674016962534858, 'b': 2.0410088421902652, 'd': -1.2602923734811284}, 'foo': {'a': -1.6340274257732716, 'c': 0.6674016962534858, 'b': 2.0410088421902652, 'd': -1.2602923734811284}, 'bar': {'a': -1.6340274257732716, 'c': 0.6674016962534858, 'b': 2.0410088421902652, 'd': -1.2602923734811284}}
{'baz': {'a': -1.6340274257732716, 'b': 2.0410088421902652, 'd': -1.2602923734811284}, 'foo': {'a': -1.6340274257732716, 'b': 2.0410088421902652, 'd': -1.2602923734811284}, 'bar': {'a': -1.6340274257732716, 'b': 2.0410088421902652, 'd': -1.2602923734811284}}
</code></pre>

<p>Intention here is to delete only <code>d['foo']['c]</code>, but all the <code>'c'</code>'s are getting deleted across <code>'foo', 'bar', 'baz'</code> .. Not sure if this has been already answered on this forum, if yes please point me to that answer.</p>

<p>You are setting each value in <code>d</code> to reference the same copy of <code>td</code>. If you want the copies to be distinct, you'll need to create more than one <code>td</code> dictionary.</p>

<p>Try this:</p>

<pre><code>#!/usr/bin/python
import numpy as np

d = {}
for col in ['foo','bar','baz']:
    td = {}
    for row in ['a','b','c','d']:
        td.setdefault(row, np.random.randn())
    d.setdefault(col, td)

print d
del d['foo']['c']
print d
</code></pre>

python