user3646519 user3646519 - 1 month ago 7x
Python Question

Python copy parts of dictionary into a new dictionary

I have a python dictionary which looks like this:

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

I need to parse the above and store it as:

{"payment_amt": "20",
"clm_list": {"dtl": [{"clm_id": "1A2345"},
{"clm_id": "9999"}]}}

Is there a right pythonic way to do it?



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.

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.

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]
        return obj

new_dict = recursively_prune_dict_keys(old_dict, keep)
print new_dict


{'clm_list': {'dtl': [{'clm_id': '1A2345'}, {'clm_id': '9999'}]}, 'payment_amt': '20'}