📜  Python – 将字典值减 K

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

Python – 将字典值减 K

有时,在使用字典时,我们可以有一个用例,我们需要在字典中将特定键的值减少 K。这似乎是一个非常直接的问题,但是当不知道密钥的存在时会出现捕获,因此有时会变成两步过程。让我们讨论可以执行此任务的某些方式。

方法 #1:使用get()
get函数可用于将不存在的键初始化为 0,然后可以递减。这样可以避免密钥不存在的问题。

# Python3 code to demonstrate working of
# Decrement Dictionary value by K
# Using get()
  
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'for' : 4, 'CS' : 5}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# Initialize K 
K = 5
  
# Using get()
# Decrement Dictionary value by K
test_dict['best'] = test_dict.get('best', 0) - K
      
# printing result 
print("Dictionary after the decrement of key : " + str(test_dict))
输出 :

方法 #2:使用defaultdict()
这个问题也可以通过使用 defaultdict 方法来解决,该方法初始化潜在的键并且在键不存在的情况下不会抛出异常。

# Python3 code to demonstrate working of
# Decrement Dictionary value by K
# Using defaultdict()
from collections import defaultdict
  
# Initialize dictionary
test_dict = defaultdict(int)
  
# printing original dictionary
print("The original dictionary : " + str(dict(test_dict)))
  
# Initialize K 
K = 5
  
# Using defaultdict()
# Decrement Dictionary value by K
test_dict['best'] -= K
      
# printing result 
print("Dictionary after the decrement of key : " + str(dict(test_dict)))
输出 :