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>I think there are two ways to avoid the duplicate references.</p>

<p>The first is to <code>append</code> a copy of the dictionary, instead of a reference to it. <code>dict</code> instances have a <code>copy</code> method, so this is easy. Just change your current <code>append</code> call to:</p>

<pre><code>outer_list.append(dict_obj.copy())`
</code></pre>

<p>The other option is to not always use the same <code>dict_obj</code> object, but rather create a separate dictionary object for each entry. In this version, you'd replace your call to <code>dict_obj.clear()</code> with:</p>

<pre><code>dict_obj = {}
</code></pre>

<p>For the second approach, you might choose to reorder things rather than doing a straight one-line replacement. You could move the setup code to the start of the loop and get rid of the reset logic at the end of the loop.</p>

<p>That is, change code that looks like this:</p>

<pre><code>outer_list = []
dict_obj = {}
for foo in whatever:
    # add stuff to dict_obj
    outer_list.append(dict_obj)
    dict_obj.clear()
</code></pre>

<p>To:</p>

<pre><code>outer_list = []
for foo in whatever:
    dict_obj = {}
    # add stuff to dict_obj
    outer_list.append(dict_obj)
</code></pre>

<p>If the logic for creating the inner dictionaries is simple enough to compute, you might even turn the whole thing into a list comprehension:</p>

<pre><code>outer_list = [{"key": value, "key2": value2} for value, value2 in some_sequence]
</code></pre>

python list dictionary