📜  Python – 字典元组值更新

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

Python – 字典元组值更新

有时,在处理元组数据时,我们在执行它的版本时可能会遇到问题,原因是它的不变性。这讨论了字典中元组值的版本。这可以在许多领域中应用,因为字典通常是 Web 开发和数据科学领域中流行的数据类型。让我们讨论一些可以解决这个问题的方法。

方法#1:使用生成器表达式+字典理解
上述功能的组合提供了一种线性暴力方式来解决这个问题。在此,我们使用生成器表达式和字典推导执行编辑任务,以使用编辑值重新制作字典。

Python3
# Python3 code to demonstrate working of
# Dictionary Tuple values update
# Using generator expression + dictionary comprehension
 
# initializing dictionary
test_dict = {'Gfg' : (5, 6), 'is' : (7, 8), 'best' : (10, 11)}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K
# performing multiplication by K
K = 3
 
# Dictionary Tuple values update
# Using generator expression + dictionary comprehension
res = {key: tuple(idx * K for idx in val)
          for key, val in test_dict.items()}
     
# printing result
print("The edited tuple values : " + str(res))


Python3
# Python3 code to demonstrate working of
# Dictionary Tuple values update
# Using map() + lambda() + dict()
 
# initializing dictionary
test_dict = {'Gfg' : (5, 6), 'is' : (7, 8), 'best' : (10, 11)}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K
# performing multiplication by K
K = 3
 
# Dictionary Tuple values update
# Using map() + lambda() + dict()
res = dict(map(lambda sub: (sub[0], (sub[1][0] * K,
               sub[1][1] * K)), test_dict.items()))
     
# printing result
print("The edited tuple values : " + str(res))


输出 :
The original dictionary is : {'Gfg': (5, 6), 'is': (7, 8), 'best': (10, 11)}
The edited tuple values : {'Gfg': (15, 18), 'is': (21, 24), 'best': (30, 33)}


方法 #2:使用 map() + lambda() + dict()
上述功能的组合也提供了解决这个问题的方法。在此,值的分配是使用 lambda() 完成的,字典的构造是使用 dict() 完成的。将逻辑扩展到每个键的任务是使用 map() 完成的。

Python3

# Python3 code to demonstrate working of
# Dictionary Tuple values update
# Using map() + lambda() + dict()
 
# initializing dictionary
test_dict = {'Gfg' : (5, 6), 'is' : (7, 8), 'best' : (10, 11)}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K
# performing multiplication by K
K = 3
 
# Dictionary Tuple values update
# Using map() + lambda() + dict()
res = dict(map(lambda sub: (sub[0], (sub[1][0] * K,
               sub[1][1] * K)), test_dict.items()))
     
# printing result
print("The edited tuple values : " + str(res))
输出 :
The original dictionary is : {'Gfg': (5, 6), 'is': (7, 8), 'best': (10, 11)}
The edited tuple values : {'Gfg': (15, 18), 'is': (21, 24), 'best': (30, 33)}