mardi 30 mars 2021

Fastest way to get values from dictionary to another dictionary in python without using if?

I need to find a way to get values from one dictionary to another, bases on key name match without using two loops \ if statement.

Main goal is to make it run more efficiently since it's a part of a larger code and run on multiple threads.

If you can keep the dictionary structure it would help

The second dict is initialized with values 0 in advanced

dict_1 = {
    "school": {
        "main": ["first_key"]
    },
    "specific": {
        "students": [
            {
                "name": "sam",
                "age": 13
            },
            {
                "name": "dan",
                "age": 9
            },
            {
                "name": "david",
                "age": 20
            },
            {
                "name": "mike",
                "age": 5
            }
        ],
        "total_students": 4
    }
}

dict_2 = {'sam': 0, 'mike': 0, 'david': 0, 'dan': 0, 'total_students': 0}

for i in dict_1["specific"]['students']:
    for x in dict_2:
        if x == i["name"]:
            dict_2[x] = i["age"]

    dict_2["total_students"] = dict_1["specific"]["total_students"]

print(dict_2)

Is there more elegant way of doing it?

Thanks!!

Aucun commentaire:

Enregistrer un commentaire