Skip to content
Advertisement

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?

Advertisement

Answer

You don’t need two loops at all! You don’t even need to initialize dict_2 in advance. Simply loop over dict_1["specific"]["students"] and assign the ages to dict_2 without an if.

for student in dict_1["specific"]["students"]:
    student_name = student["name"]
    student_age = student["age"]
    dict_2[student_name] = student_age

You could also write this as a comprehension:

dict_2 = {student["name"]: student["age"] for student in dict_1["specific"]["students"]}

Both these give the following dict_2:

{'sam': 13, 'dan': 9, 'david': 20, 'mike': 5}

Then you can set dict_2["total_students"] like you already do, but outside any loops.

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

If you only want to assign ages for students already in dict_2, you need the if. However, you can still do this with a single loop instead of two. :

for student in dict_1["specific"]["students"]:
    student_name = student["name"]
    if student_name not in dict_2:
        continue # skip the rest of this loop

    student_age = student["age"]
    dict_2[student_name] = student_age

Both these approaches use a single loop, so they’re going to be faster than your two-loop approach.

Advertisement