从字典中的第 K 个键的值中删除第 N 个元素的Python程序
给定一个带有值列表的字典,我们的任务是编写一个Python程序来从第 K 个键的值中删除 N 个元素。
例子:
Input : test_dict = {“gfg” : [9, 4, 5, 2, 3, 2], “is” : [1, 2, 3, 4, 3, 2], “best” : [2, 2, 2, 3, 4]}, K, N = “gfg”, 2
Output : {‘gfg’: [9, 4, 5, 3], ‘is’: [1, 2, 3, 4, 3, 2], ‘best’: [2, 2, 2, 3, 4]}
Explanation : 2 removed from “gfg” key’s value list.
Input : test_dict = {“gfg” : [9, 4, 5, 2, 3, 2], “is” : [1, 2, 3, 4, 3, 2], “best” : [2, 2, 2, 3, 4]}, K, N = “gfg”, 4
Output : {‘gfg’: [9, 5, 2, 3, 2], ‘is’: [1, 2, 3, 4, 3, 2], ‘best’: [2, 2, 2, 3, 4]}
Explanation : 4 removed from “gfg” key’s value list.
方法#1:使用循环+条件语句
在这种情况下,所有键及其值的重新分配都完成了,当 K 键出现时,其值列表中的 N 出现被忽略。
Python3
# Python3 code to demonstrate working of
# Remove N from K key's value in dictionary values list
# Using loop + conditional statements
# initializing dictionary
test_dict = {"gfg" : [9, 4, 5, 2, 3, 2],
"is" : [1, 2, 3, 4, 3, 2],
"best" : [2, 2, 2, 3, 4]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K, N
K, N = "gfg", 2
res = dict()
for key, val in test_dict.items():
# reassigning omitting desired number
res[key] = (val if key != K else [idx for idx in val if idx != N])
# printing result
print("The altered dictionary : " + str(res))
Python3
# Python3 code to demonstrate working of
# Remove N from K key's value in dictionary values list
# Using dictionary comprehension
# initializing dictionary
test_dict = {"gfg" : [9, 4, 5, 2, 3, 2],
"is" : [1, 2, 3, 4, 3, 2],
"best" : [2, 2, 2, 3, 4]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K, N
K, N = "gfg", 2
# dictionary comprehension used for shorthand
res = {key : (val if key != K else [idx for idx in val if idx != N]) for key, val in test_dict.items()}
# printing result
print("The altered dictionary : " + str(res))
输出:
The original dictionary is : {‘gfg’: [9, 4, 5, 2, 3, 2], ‘is’: [1, 2, 3, 4, 3, 2], ‘best’: [2, 2, 2, 3, 4]}
The altered dictionary : {‘gfg’: [9, 4, 5, 3], ‘is’: [1, 2, 3, 4, 3, 2], ‘best’: [2, 2, 2, 3, 4]}
方法#2:使用字典理解
在这种情况下,我们执行与上述方法类似的任务,不同之处在于使用字典理解而不是使用传统循环遍历键。
蟒蛇3
# Python3 code to demonstrate working of
# Remove N from K key's value in dictionary values list
# Using dictionary comprehension
# initializing dictionary
test_dict = {"gfg" : [9, 4, 5, 2, 3, 2],
"is" : [1, 2, 3, 4, 3, 2],
"best" : [2, 2, 2, 3, 4]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K, N
K, N = "gfg", 2
# dictionary comprehension used for shorthand
res = {key : (val if key != K else [idx for idx in val if idx != N]) for key, val in test_dict.items()}
# printing result
print("The altered dictionary : " + str(res))
输出:
The original dictionary is : {‘gfg’: [9, 4, 5, 2, 3, 2], ‘is’: [1, 2, 3, 4, 3, 2], ‘best’: [2, 2, 2, 3, 4]}
The altered dictionary : {‘gfg’: [9, 4, 5, 3], ‘is’: [1, 2, 3, 4, 3, 2], ‘best’: [2, 2, 2, 3, 4]}