Home > other >  Python Creating new dict from specific keys in other dict (nested)
Python Creating new dict from specific keys in other dict (nested)

Time:09-26

(Please note I searched and couldn't find an answer for this type of nested, with dict and lists, and with keeping keys names and values).

I'm trying to create a new dict from existing dict with specific keys-value pairs that I need.

Example/origin dict:

{
    "test1":{
        "test2":[
            
        ]
    },
    "test3":[
        
    ],
    "test4":{
        "test5":0,
        "what":{
            "in":"2",
            "out":"4"
        }
    },
    "test12":[
        {
            "in2":"a",
            "out2":"b"
        },
        {
            "in2":"a33",
            "out2":"b33"
        }
    ],
    "test9":255
}

I want to select keys for example: ['test1'], ['test4'], ['test12']['in2'] in such way that the result dict will be:

{
    "test1":{
        "test2":[
            
        ]
    },
    "test4":{
        "test5":0,
        "what":{
            "in":"2",
            "out":"4"
        }
    },
    "test12":[
        {
            "in2":"a"
        },
        {
            "in2":"a33"
        }
    ]
}

I'm aware its possible to do manually, i want to see the pythonic way :)

Thanks!!!

CodePudding user response:

Try a dictionary comprehension with isinstance list:

>>> {k: ([{'in2': i['in2']} for i in v] if isinstance(v, list) else v) for k, v in dct.items() if not isinstance(v, int) and v}
{'test1': {'test2': []},
 'test4': {'test5': 0, 'what': {'in': '2', 'out': '4'}},
 'test12': [{'in2': 'a'}, {'in2': 'a33'}]}
>>> 

CodePudding user response:

Like this:-

D = {
    "test1": {
        "test2": [

        ]
    },
    "test3": [

    ],
    "test4": {
        "test5": 0,
        "what": {
            "in": "2",
            "out": "4"
        }
    },
    "test12": [
        {
            "in2": "a",
            "out2": "b"
        },
        {
            "in2": "a33",
            "out2": "b33"
        }
    ],
    "test9": 255
}

E = {}
for k in ['test1', 'test4', 'test12']:
    E[k] = D[k]


print(E)

You don't need 'in2' in your list of keys because it's already included in one of the sub-dictionaries

  • Related