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

JavaScript

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.

JavaScript

You could also write this as a comprehension:

JavaScript

Both these give the following dict_2:

JavaScript

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

JavaScript

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. :

JavaScript

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

Advertisement