如果字典等于 K,则更改字典值的Python程序
给定一个字典,如果它等于 K,就改变它的值。
Input : test_dict = {“Gfg”: 4, “is”: 8, “best”: 10, “for”: 8, “geeks”: 19}, K = 8, repl_val = 25
Output : {‘Gfg’: 4, ‘is’: 25, ‘best’: 10, ‘for’: 25, ‘geeks’: 19}
Explanation : All values with 8 converted to 25.
Input : test_dict = {“Gfg”: 6, “is”: 8, “best”: 10, “for”: 8, “geeks”: 19}, K = 6, repl_val = 25
Output : {‘Gfg’: 25, ‘is’: 8, ‘best’: 10, ‘for’: 8, ‘geeks’: 19}
Explanation : All values with 6 converted to 25.
方法#1:使用循环
这是可以执行此任务的粗暴方式。在这里,我们迭代字典的所有键和值,如果找到匹配项,则执行所需的转换。
Python3
# Python3 code to demonstrate working of
# Change value if value equals K in dictionary
# Using loop
# initializing dictionary
test_dict = {"Gfg": 4, "is": 8, "best": 10, "for": 8, "geeks": 19}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 8
# initializing repl_val
repl_val = 20
# iterating dictionary
for key, val in test_dict.items():
# checking for required value
if val == K:
test_dict[key] = repl_val
# printing result
print("The dictionary after values replacement : " + str(test_dict))
Python3
# Python3 code to demonstrate working of
# Change value if value equals K in dictionary
# Using dictionary comprehension
# initializing dictionary
test_dict = {"Gfg": 4, "is": 8, "best": 10, "for": 8, "geeks": 19}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 8
# initializing repl_val
repl_val = 20
# one-liner to solve for dictionary
res = {key : repl_val if val == K else val for key, val in test_dict.items()}
# printing result
print("The dictionary after values replacement : " + str(res))
The original dictionary is : {‘Gfg’: 4, ‘is’: 8, ‘best’: 10, ‘for’: 8, ‘geeks’: 19}
The dictionary after values replacement : {‘Gfg’: 4, ‘is’: 20, ‘best’: 10, ‘for’: 20, ‘geeks’: 19}
方法#2:使用字典理解
这是解决此问题的一种单行替代方法。在这种情况下,我们迭代并分配创建一个新字典,而不是像上面的方法那样进行就地替换。
蟒蛇3
# Python3 code to demonstrate working of
# Change value if value equals K in dictionary
# Using dictionary comprehension
# initializing dictionary
test_dict = {"Gfg": 4, "is": 8, "best": 10, "for": 8, "geeks": 19}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 8
# initializing repl_val
repl_val = 20
# one-liner to solve for dictionary
res = {key : repl_val if val == K else val for key, val in test_dict.items()}
# printing result
print("The dictionary after values replacement : " + str(res))
The original dictionary is : {‘Gfg’: 4, ‘is’: 8, ‘best’: 10, ‘for’: 8, ‘geeks’: 19}
The dictionary after values replacement : {‘Gfg’: 4, ‘is’: 20, ‘best’: 10, ‘for’: 20, ‘geeks’: 19}