Python – Variable Operations Dictionary update
Sometimes, while working with Python dictionaries we can have a problem in which we need to perform a population of dictionary values using assigned variables after certain operation among them. This can have application in day-day programming. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using lambda + dictionary comprehension
The combination of above functions can be used to solve this problem. In this, we perform the assignment using dictionary comprehension and values computations using lambda functions.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Python3
# Python3 code to demonstrate working of# Variable Operations Dictionary update# Using lambda + dictionary comprehension# helper functionshelper_fnc = {'Gfg': lambda: x + y, 'best': lambda: x * y}# initializing variablesx = 6y = 7# Variable Operations Dictionary update# Using lambda + dictionary comprehensionres = {key: val() for key, val in hlper_fnc.items()}# printing resultprint("The Initialized dictionary : " + str(res)) |
The Initialized dictionary : {'best': 42, 'Gfg': 13}
Method #2 : Using operators library
This task can also be performed using above functionality. In this, we use inbuilt operations provided by the operator library to achieve this task.
Python3
# Python3 code to demonstrate working of# Variable Operations Dictionary update# Using lambda + dictionary comprehensionfrom operator import add, mul# helper functionshelper_fnc = {'Gfg': add, 'best': mul}# initializing variablesx = 6y = 7# Variable Operations Dictionary update# Using lambda + dictionary comprehensionres = {'Gfg' : hlper_fnc['Gfg'](x, y), 'best' : hlper_fnc['best'](x, y)}# printing resultprint("The Initialized dictionary : " + str(res)) |
The Initialized dictionary : {'best': 42, 'Gfg': 13}


