How do I get specific keys and their values from nested dict in python?

Question:

I need help, please be kind I’m a beginner.
I have a nested dict like this:

dict_ = {
 "timestamp": "2022-11-18T10: 10: 49.301Z",
 "name" : "example",
 "person":{
    "birthyear": "2002"
    "birthname": "Examply"
 },
 "order":{
    "orderId": "1234"
    "ordername": "onetwothreefour"
 }
}

How do I get a new dict like:

new_dict = {"timestamp": "2022-11-18T10: 10: 49.301Z", "birthyear": "2002", "birthname": "Examply", "orderId": "1234"} 

I tried the normal things I could google.
But I only found solutions like getting the values without the keys back or it only works for flatten dicts.
Last thing I tried:

new_dict = {key: msg[key] for key in msg.keys() & {'timestamp', 'birthyear', 'birthname', 'orderId'}

This do not work for the nested dict.
May someone has an easy option for it.

Asked By: JazCodes

||

Answers:

A general approach:

dict_ = {
    "timestamp": "2022-11-18T10: 10: 49.301Z",
    "name": "example",
    "person": {
        "birthyear": "2002",
        "birthname": "Examply"
    },
    "order": {
        "orderId": "1234",
        "ordername": "onetwothreefour"
    }
}


def nested_getitem(d, keys):
    current = d
    for key in keys:
        current = current[key]
    return current


new_dict = {"timestamp": nested_getitem(dict_, ["timestamp"]),
            "birthyear": nested_getitem(dict_, ["person", "birthyear"]),
            "birthname": nested_getitem(dict_, ["person", "birthname"]),
            "orderId": nested_getitem(dict_, ["order", "orderId"]),
            }
print(new_dict)

Output

{'timestamp': '2022-11-18T10: 10: 49.301Z', 'birthyear': '2002', 'birthname': 'Examply', 'orderId': '1234'}
Answered By: Dani Mesejo
dict_ = {
 "timestamp": "2022-11-18T10: 10: 49.301Z",
 "name" : "example",
 "person":{
    "birthyear": "2002",
    "birthname": "Examply"
 },
 "order":{
    "orderId": "1234",
    "ordername": "onetwothreefour"
 }
}


def get_new_dict(dict_):
    new_dict = {'timestamp': dict_['timestamp'],
                'birthyear':dict_['person']['birthyear'], 
                'birthname': dict_['person']['birthname'], 
                'orderId': dict_['order']['orderId']
               }
    
    return new_dict
    
new_dict = get_new_dict(dict_)

print(new_dict)

output:

{'timestamp': '2022-11-18T10: 10: 49.301Z', 'birthyear': '2002', 'birthname': 'Examply', 'orderId': '1234'}
Answered By: Jamiu Shaibu
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.