Python – 从字典中删除第 K 个键
很多时候,在使用Python时,我们可能会遇到需要删除字典的第 K 个键的情况。这对于Python 3.8 + 版本很有用,其中键排序类似于插入顺序。让我们讨论可以执行此任务的某些方式。
例子:
Input : test_dict = {“Gfg” : 20, “is” : 36, “best” : 100, “for” : 17, “geeks” : 1} , K = 4
Output : {‘Gfg’: 20, ‘is’: 36, ‘best’ : 100, ‘geeks’: 1}
Explanation : 4th index, for is removed.
Input : test_dict = {“Gfg” : 20, “is” : 36, “best” : 100, “for” : 17, “geeks” : 1} , K = 2
Output : {‘Gfg’: 20, ‘best’ : 100, ‘for’ : 17, ‘geeks’: 1}
Explanation : 2nd index, ‘is’ is removed.
方法 #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))
输出:
The original dictionary is : {‘Gfg’: 20, ‘is’: 36, ‘best’: 100, ‘for’: 17, ‘geeks’: 1}
Required dictionary after removal : {‘Gfg’: 20, ‘is’: 36, ‘for’: 17, ‘geeks’: 1}
方法#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))
输出:
The original dictionary is : {‘Gfg’: 20, ‘is’: 36, ‘best’: 100, ‘for’: 17, ‘geeks’: 1}
Required dictionary after removal : {‘Gfg’: 20, ‘is’: 36, ‘for’: 17, ‘geeks’: 1}