Python|更新字典中的值列表
在使用以列表为值的字典时,总是容易受到更新其值的影响。在这种情况下,执行此任务的方法或速记可能很方便。这可能发生在 Web 开发领域。让我们讨论可以执行此任务的某些方式。
方法#1:使用列表推导
执行此特定任务的简单方法,在此,我们只需提取键,然后在打包列表中以列表综合格式迭代它的值。这解决了问题。
# Python3 code to demonstrate working of
# Updating value list in dictionary
# Using list comprehension
# Initialize dictionary
test_dict = {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Using list comprehension
# Updating value list in dictionary
test_dict['gfg'] = [x * 2 for x in test_dict['gfg']]
# printing result
print("Dictionary after updation is : " + str(test_dict))
输出 :
The original dictionary : {‘is’: 2, ‘gfg’: [1, 5, 6], ‘best’: 3}
Dictionary after updation is : {‘is’: 2, ‘gfg’: [2, 10, 12], ‘best’: 3}
方法 #2:使用map()
+ lambda
可以使用上述两个函数的组合来执行此任务,其中我们使用 map() 将更新函数链接到值列表的每个元素,并使用 lambda 来指定更新。
# Python3 code to demonstrate working of
# Updating value list in dictionary
# Using map() + lambda
# Initialize dictionary
test_dict = {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Using map() + lambda
# Updating value list in dictionary
test_dict['gfg'] = list(map(lambda x:x * 2, test_dict['gfg']))
# printing result
print("Dictionary after updation is : " + str(test_dict))
输出 :
The original dictionary : {‘is’: 2, ‘gfg’: [1, 5, 6], ‘best’: 3}
Dictionary after updation is : {‘is’: 2, ‘gfg’: [2, 10, 12], ‘best’: 3}