📜  Python|每个字典键上的 K 模

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

Python|每个字典键上的 K 模

有时,在使用字典时,我们可能会遇到一个问题,即我们需要对键的每个值执行特定操作,例如对每个键取 K 模。此类问题可能发生在 Web 开发领域。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环
这是可以执行此任务的简单方法。在此我们简单地运行一个循环来遍历字典中的每个键并执行所需的 K 模运算。

# Python3 code to demonstrate working of
# K modulo on each Dictionary Key
# Using loop
  
# Initialize dictionary
test_dict = {'gfg' : 6, 'is' : 4, 'best' : 7}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# initializing K 
K = 4
  
# Using loop
# K modulo on each Dictionary Key
for key in test_dict: 
    test_dict[key] %= 4
  
# printing result 
print("The dictionary after mod K each key's value : " + str(test_dict))
输出 :
The original dictionary : {'is': 4, 'best': 7, 'gfg': 6}
The dictionary after mod K each key's value : {'is': 0, 'best': 3, 'gfg': 2}

方法 #2:使用update() + 字典理解
执行此任务的替代单线,上述功能的组合可用于执行此特定任务。更新函数用于对字典执行 %K。

# Python3 code to demonstrate working of
# K modulo on each Dictionary Key
# Using update() + dictionary comprehension
  
# Initialize dictionary
test_dict = {'gfg' : 6, 'is' : 4, 'best' : 7}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# initializing K 
K = 4
  
# Using update() + dictionary comprehension
# K modulo on each Dictionary Key
test_dict.update((x, y % K) for x, y in test_dict.items())
  
# printing result 
print("The dictionary after mod K each key's value : " + str(test_dict))
输出 :
The original dictionary : {'is': 4, 'best': 7, 'gfg': 6}
The dictionary after mod K each key's value : {'is': 0, 'best': 3, 'gfg': 2}