📜  Python – 变量操作字典更新

📅  最后修改于: 2022-05-13 01:54:59.540000             🧑  作者: Mango

Python – 变量操作字典更新

有时,在使用Python字典时,我们可能会遇到一个问题,即我们需要在其中的某些操作之后使用分配的变量来执行一组字典值。这可以在日常编程中应用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用 lambda + 字典理解
上述功能的组合可以用来解决这个问题。在此,我们使用字典理解和使用 lambda 函数的值计算来执行分配。

Python3
# Python3 code to demonstrate working of
# Variable Operations Dictionary update
# Using lambda + dictionary comprehension
 
# helper functions
helper_fnc = {'Gfg': lambda: x + y,
         'best': lambda: x * y}
 
# initializing variables
x = 6
y = 7
 
# Variable Operations Dictionary update
# Using lambda + dictionary comprehension
res = {key: val() for key, val in hlper_fnc.items()}
 
# printing result
print("The Initialized dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of
# Variable Operations Dictionary update
# Using lambda + dictionary comprehension
from operator import add, mul
 
# helper functions
helper_fnc = {'Gfg': add,
         'best': mul}
 
# initializing variables
x = 6
y = 7
 
# Variable Operations Dictionary update
# Using lambda + dictionary comprehension
res = {'Gfg' : hlper_fnc['Gfg'](x, y), 'best' : hlper_fnc['best'](x, y)}
 
# printing result
print("The Initialized dictionary : " + str(res))


输出 :
The Initialized dictionary : {'best': 42, 'Gfg': 13}


方法#2:使用运算符库
也可以使用上述功能执行此任务。在此,我们使用运算符库提供的内置操作来完成此任务。

Python3

# Python3 code to demonstrate working of
# Variable Operations Dictionary update
# Using lambda + dictionary comprehension
from operator import add, mul
 
# helper functions
helper_fnc = {'Gfg': add,
         'best': mul}
 
# initializing variables
x = 6
y = 7
 
# Variable Operations Dictionary update
# Using lambda + dictionary comprehension
res = {'Gfg' : hlper_fnc['Gfg'](x, y), 'best' : hlper_fnc['best'](x, y)}
 
# printing result
print("The Initialized dictionary : " + str(res))
输出 :
The Initialized dictionary : {'best': 42, 'Gfg': 13}