📜  Python – 从字典中删除第 K 个键

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

Python – 从字典中删除第 K 个键

很多时候,在使用Python时,我们可能会遇到需要删除字典的第 K 个键的情况。这对于Python 3.8 + 版本很有用,其中键排序类似于插入顺序。让我们讨论可以执行此任务的某些方式。

例子:

方法 #1:使用 del + 循环

这是可以执行此任务的方法之一。在这里,我们迭代键和计数器,当我们得到键时,我们执行它的删除。这将执行就地移除。

Python3
# Python3 code to demonstrate working of 
# Remove Kth key from dictionary
# Using loop
  
# initializing dictionary
test_dict = {"Gfg" : 20, "is" : 36, "best" : 100,
             "for" : 17, "geeks" : 1} 
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing size 
K = 3
  
cnt = 0
for key in test_dict:
    cnt += 1
      
    # delete key if counter is equal to K
    if cnt == K:
        del test_dict[key]
        break
      
# printing result 
print("Required dictionary after removal : " + str(test_dict))


Python3
# Python3 code to demonstrate working of 
# Remove Kth key from dictionary
# Using Remove Kth key from dictionary
  
# initializing dictionary
test_dict = {"Gfg" : 20, "is" : 36, "best" : 100,
             "for" : 17, "geeks" : 1} 
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing size 
K = 3
  
# dictionary comprehension remakes dictionary, 
# rather than removing
res = {key: val for key, val in test_dict.items() 
       if key != list(test_dict.keys())[K - 1]}
      
# printing result 
print("Required dictionary after removal : " + str(res))


输出:

方法#2:使用keys() + 字典理解

这是可以执行此任务的另一种方式。在这种情况下,我们重新创建字典而不包含所需的键,通过使用 keys() 提取要删除的键,我们将除必需之外的所有键都包含到新字典中。

蟒蛇3

# Python3 code to demonstrate working of 
# Remove Kth key from dictionary
# Using Remove Kth key from dictionary
  
# initializing dictionary
test_dict = {"Gfg" : 20, "is" : 36, "best" : 100,
             "for" : 17, "geeks" : 1} 
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing size 
K = 3
  
# dictionary comprehension remakes dictionary, 
# rather than removing
res = {key: val for key, val in test_dict.items() 
       if key != list(test_dict.keys())[K - 1]}
      
# printing result 
print("Required dictionary after removal : " + str(res))

输出: