Python – 提取选择性键的值,包括嵌套键
有时,在使用Python字典时,我们可能会遇到需要提取选择性键值的问题。这个问题之前已经解决了,但有时,我们可以有多个嵌套,并且某些键可能存在于内部记录中。这个问题迎合了提取键值的所有嵌套。让我们讨论一下可以解决此任务的某种方式。
Input :
test_dict = {‘gfg’: {‘geeks’: {‘best’ : 3}}}
key_list = [‘best’, ‘geeks’]
Output : {‘geeks’: {‘best’: 3}, ‘best’: 3}
Input :
test_dict = {‘gfg’: {‘geek’: {‘good’ : 3}}}
key_list = [‘best’, ‘geeks’]
Output : {}
方法:使用递归+循环+产量
上述功能的组合可以用来解决这个问题。在此,我们执行使用条件语句检查键并使用递归检查嵌套的任务。 yield运算符用于在发生分配时动态返回键。
Python3
# Python3 code to demonstrate working of
# Extract selective keys' values [ Including Nested Keys ]
# Using recursion + loop + yield
def get_vals(test_dict, key_list):
for i, j in test_dict.items():
if i in key_list:
yield (i, j)
yield from [] if not isinstance(j, dict) else get_vals(j, key_list)
# initializing dictionary
test_dict = {'gfg': {'is': {'best' : 3}}, 'for': {'all' : 4}, 'geeks': 5}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing keys list
key_list = ['best', 'geeks']
# Extract selective keys' values [ Including Nested Keys ]
# Using recursion + loop + yield
res = dict(get_vals(test_dict, key_list))
# printing result
print("The extracted values : " + str(res))
输出 :
The original dictionary is : {'gfg': {'is': {'best': 3}}, 'for': {'all': 4}, 'geeks': 5}
The extracted values : {'best': 3, 'geeks': 5}