Python – 提取不在值中的键
有时,在使用Python字典时,我们可能会遇到一个问题,即我们需要获取所有未出现在值列表中的键。这可以在诸如日间编程之类的领域中具有应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用set() + values() + keys()
+ loop
这是处理此任务的粗暴方式。在此,我们测试值列表中的元素,并继续将它们添加到单独的列表中。然后我们使用 keys() 从提取的键中减去它。
# Python3 code to demonstrate working of
# Extracting keys not in values
# Using set() + keys() + values() + loop
# initializing Dictionary
test_dict = {3 : [1, 3, 4], 5 : [1, 2], 6 : [4, 3], 4 : [1, 3]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Extracting keys not in values
# Using set() + keys() + values() + loop
temp1 = set(test_dict.keys())
temp2 = set()
for ele in test_dict.values():
temp2.update(ele)
res = list(temp1 - temp2)
# printing result
print("The extracted keys are : " + str(res))
输出 :
The original dictionary is : {3: [1, 3, 4], 4: [1, 3], 5: [1, 2], 6: [4, 3]}
The extracted keys are : [5, 6]
方法 #2:使用生成器表达式 + set()
此方法与上述方法类似。不同之处在于它使用生成器表达式以紧凑格式作为一种线性方式执行。
# Python3 code to demonstrate working of
# Extracting keys not in values
# Using generator expression + set()
# initializing Dictionary
test_dict = {3 : [1, 3, 4], 5 : [1, 2], 6 : [4, 3], 4 : [1, 3]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Extracting keys not in values
# Using generator expression + set()
res = list(set(test_dict) - set(ele for sub in test_dict.values() for ele in sub))
# printing result
print("The extracted keys are : " + str(res))
输出 :
The original dictionary is : {3: [1, 3, 4], 4: [1, 3], 5: [1, 2], 6: [4, 3]}
The extracted keys are : [5, 6]