📜  如果字典等于 K,则更改字典值的Python程序

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

如果字典等于 K,则更改字典值的Python程序

给定一个字典,如果它等于 K,就改变它的值。

方法#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))


输出

方法#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))
输出