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>Personally, I would go with a straightforward copy of the exact keys you want to keep in the example you posted (see Rob's answer), if the input is always exactly like you listed. Keep it simple.</p>

<p>However, if you can't rely on the input to always have the same exact structure, you can still reduce it to only include the expected keys with a recursive function which uses dict comprehensions.</p>

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

keep = ["payment_amt", "clm_list", "dtl", "clm_id"]

def recursively_prune_dict_keys(obj, keep):
    if isinstance(obj, dict):
        return {k: recursively_prune_dict_keys(v, keep) for k, v in obj.items() if k in keep}
    elif isinstance(obj, list):
        return [recursively_prune_dict_keys(item, keep) for item in obj]
    else:
        return obj

new_dict = recursively_prune_dict_keys(old_dict, keep)
print new_dict
</code></pre>

<p>output:</p>

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

python dictionary