Python – 从嵌套项中过滤键
有时,在使用Python字典时,我们可能会遇到一个问题,即我们需要提取具有特定键值对的键作为其嵌套项的一部分。这种问题在Web开发领域很常见。让我们讨论可以执行此任务的某些方式。
Input : test_dict = {‘gfg’ : {‘best’ : 10, ‘good’ : 5}}
Output : [‘gfg’]
Input : test_dict = {‘gfg’ : {‘best’ : 10, ‘good’ : 12}}
Output : []
方法 #1:使用循环 + __contains__
上述功能的组合构成了执行此任务的蛮力方式。在此,我们使用循环对每个键进行迭代,并使用 __contains__ 检查值是否存在。
# Python3 code to demonstrate working of
# Filter Key from Nested item
# Using loop + __contains__
# initializing dictionary
test_dict = {'gfg' : {'best' : 4, 'good' : 5},
'is' : {'better' : 6, 'educational' : 4},
'CS' : {'priceless' : 6},
'Maths' : {'good' : 5}}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing dictionary
que_dict = {'good' : 5}
# Filter Key from Nested item
# Using loop + __contains__
res = []
for key, val in test_dict.items():
if(test_dict[key].__contains__('good')):
if(test_dict[key]['good'] == que_dict['good']):
res.append(key)
# printing result
print("Match keys : " + str(res))
The original dictionary : {‘CS’: {‘priceless’: 6}, ‘is’: {‘better’: 6, ‘educational’: 4}, ‘gfg’: {‘good’: 5, ‘best’: 4}, ‘Maths’: {‘good’: 5}}
Match keys : [‘gfg’, ‘Maths’]
方法 #2:使用字典理解 + get()
上述功能的组合提供了另一种解决这个问题的方法。在此,我们使用 get() 检查元素是否存在。
# Python3 code to demonstrate working of
# Filter Key from Nested item
# Using dictionary comprehension + get()
# initializing dictionary
test_dict = {'gfg' : {'best' : 4, 'good' : 5},
'is' : {'better' : 6, 'educational' : 4},
'CS' : {'priceless' : 6},
'Maths' : {'good' : 5}}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing dictionary
que_dict = {'good' : 5}
# Filter Key from Nested item
# Using dictionary comprehension + get()
res = [ idx for idx in test_dict if test_dict[idx].get('good') == que_dict['good'] ]
# printing result
print("Match keys : " + str(res))
The original dictionary : {‘CS’: {‘priceless’: 6}, ‘is’: {‘better’: 6, ‘educational’: 4}, ‘gfg’: {‘good’: 5, ‘best’: 4}, ‘Maths’: {‘good’: 5}}
Match keys : [‘gfg’, ‘Maths’]