Python - 从字典中删除不相交的元组键
有时,在使用Python字典时,我们可能会遇到一个问题,即我们需要根据与其他列表中的任何一个元素存在键匹配的键存在来从记录中删除元组键。这类问题可以在数据域中应用。让我们讨论可以执行此任务的某些方式。
Input : test_dict = {(9, 3) : 4, (‘is’, 6) : 2, (‘for’, 9) : ‘geeks’}
Output : {}
Input : test_dict = {(‘is’, 9): 2, (‘for’, 8): 7}
Output : {(‘for’, 8): 7}
方法#1:使用循环
这是可以执行此任务的方式之一。在此我们执行字典键的迭代并检查是否存在所需的任何键并相应地执行删除。
# Python3 code to demonstrate working of
# Remove Disjoint Tuple keys from Dictionary
# Using loop
# initializing dictionary
test_dict = {('Gfg', 3) : 4, ('is', 6) : 2, ('best', 10) : 3, ('for', 9) : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing List
rem_list = [9, 'is']
# Remove Disjoint Tuple keys from Dictionary
# Using loop
res = dict()
for idx in test_dict:
if idx[0] not in rem_list and idx[1] not in rem_list:
res[idx] = test_dict[idx]
# printing result
print("Dictionary after removal : " + str(res))
The original dictionary : {(‘Gfg’, 3): 4, (‘best’, 10): 3, (‘for’, 9): ‘geeks’, (‘is’, 6): 2}
Dictionary after removal : {(‘Gfg’, 3): 4, (‘best’, 10): 3}
方法 #2:使用set() + dictionary comprehension + isdisjoint()
上述功能的组合也可以用来解决这个问题。在此,我们使用 isdisjoint() 执行比较任务。
# Python3 code to demonstrate working of
# Remove Disjoint Tuple keys from Dictionary
# Using set() + dictionary comprehension + isdisjoint()
# initializing dictionary
test_dict = {('Gfg', 3) : 4, ('is', 6) : 2, ('best', 10) : 3, ('for', 9) : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing List
rem_list = [9, 'is']
# Remove Disjoint Tuple keys from Dictionary
# Using set() + dictionary comprehension + isdisjoint()
res = {keys: val for keys, val in test_dict.items() if set(keys).isdisjoint(rem_list)}
# printing result
print("Dictionary after removal : " + str(res))
The original dictionary : {(‘Gfg’, 3): 4, (‘best’, 10): 3, (‘for’, 9): ‘geeks’, (‘is’, 6): 2}
Dictionary after removal : {(‘Gfg’, 3): 4, (‘best’, 10): 3}