Python copy parts of dictionary into a new dictionary
<p>I have a python dictionary which looks like this:</p>

<pre><code>old_dict={"payment_amt": "20",
          "chk_nr": "321749",
          "clm_list": {"dtl": [{"clm_id": "1A2345", "name": "John"},
                               {"clm_id": "9999", "name": "Jack"}]}}
</code></pre>

<p>I need to parse the above and store it as:</p>

<pre><code>{"payment_amt": "20",
 "clm_list": {"dtl": [{"clm_id": "1A2345"},
                      {"clm_id": "9999"}]}}
</code></pre>

<p>Is there a right pythonic way to do it?</p>

<p>Thanks</p>

<p>You could create a "template" dictionary/list/whatever and define a recursive method that traverses both the input object (some sort of nested list/dictionary thing) and the template in parallel and just keeps those elements that are in the respective place in the template. In a basic version, this could look like this (but could certainly be extended to cover more cases):</p>

<pre><code>def prune_dict(obj, template):
    if template is None:
        return obj
    if isinstance(template, dict):
        return {key: prune_dict(obj[key], template[key]) for key in template}
    if isinstance(template, list):
        return [prune_dict(x, template[0]) for x in obj]
</code></pre>

<p>Here, <code>template</code> is assumed to be another dictionary or list. <code>None</code> is used to denote "leafs" in the structure. For <code>list</code>, the template is assumed to hold only one element, that is used as template for all the list's elements. For <code>dict</code>, it will retain all those values that are represented in the template.</p>

<p>Applied to your use case:</p>

<pre><code>&gt;&gt;&gt; tmpl = {"payment_amt": None, "clm_list": {"dtl": [{"clm_id": None}]}}
&gt;&gt;&gt; prune_dict(old_dict, tmpl)
{'clm_list': {'dtl': [{'clm_id': '1A2345'}, {'clm_id': '9999'}]}, 'payment_amt': '20'}
</code></pre>

python dictionary