python create list of dictionaries without reference
<p>I have a requirement in which I need create dictionary objects with duplicate keys embedded into a list object, something like this:</p>

<pre><code>[{ "key": "ABC" },{ "key": "EFG" } ]
</code></pre>

<p>I decided to have a top level list initialized to empty like <code>outer_list=[]</code> and a placeholder dictionary object like <code>dict_obj= {}</code>. Next I keep adding elements to my list using the following steps:</p>

<ol>
<li>assign <code>{ "key": "ABC" }</code> to dict_obj using <code>dict_obj["key"]="ABC"</code></li>
<li>Add this object to the list using <code>outer_list.append(dict_obj)</code></li>
<li>Flush/pop the key/items in dictionary object using <code>dict_obj.clear()</code></li>
<li>Repeat steps 1 to 3 based on the number of key/item combinations in my data</li>
</ol>

<p>Issue: the <code>outer_list</code> object maintains a reference to the original <code>dict_obj</code> and if the <code>dict_obj</code> is flushed or a new key/item is added it changes accordingly. So finally, I end up with this <code>[{ "key": "EFG" },{ "key": "EFG" } ]</code> instead of <code>[{ "key": "ABC" },{ "key": "EFG" } ]</code></p>

<p>Please guide me with some workarounds if possible.</p>

<p>The following should be self-explanatory:</p>

<pre><code># object reuse
d = {}
l = []
d['key'] = 'ABC'
l.append(d)
d.clear()
print(l) # [{}] : cleared!
d['key'] = 'EFG'
l.append(d)
print(l) # [{'key': 'EFG'}, {'key': 'EFG'}]


# explicit creation of new objects
d = {}
l  = []
d['key'] = 'ABC'
l.append(d)
print(l)
d = {}
d['key'] = 'EFG'
l.append(d)
print(l)
</code></pre>

python list dictionary