Python|获取字典中的总键
有时,在使用Python字典时,可能会遇到一个问题,即需要获取整个字典中存在的键的确切数量,包括嵌套的字典。让我们讨论可以执行此任务的某些方式。
方法 #1:使用递归 + items() + sum() + len()
可以使用上述功能的组合来执行此任务。在此,我们检查嵌套是否为 not 的字典,然后使用items()
提取它的键,然后使用相应的函数对其查找长度求和。
# Python3 code to demonstrate working of
# Get total keys in dictionary
# Using recursion + items() + sum() + len()
# Utility function to perform task
def total_keys(test_dict):
return (0 if not isinstance(test_dict, dict)
else len(test_dict) + sum(total_keys(val) for val in test_dict.values()))
# Initialize dictionary
test_dict = { 'gfg' : { 'is' : 1, 'best' : { 'for' : {'geeks' :4}}}}
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Using recursion + items() + sum() + len()
# Get total keys in dictionary
res = total_keys(test_dict)
# printing result
print("Number of keys in dictionary is : " + str(res))
输出 :
The original dictionary is : {‘gfg’: {‘best’: {‘for’: {‘geeks’: 4}}, ‘is’: 1}}
Number of keys in dictionary is : 5
方法 #2:使用yield()
+ 递归
也可以使用上述功能的组合来执行此任务。这只是执行此任务的另一种方式。返回中间结果,因此这是 2 中更有效的方法。
# Python3 code to demonstrate working of
# Get total keys in dictionary
from collections import Mapping
# Utility function to perform task
def total_keys(test_dict):
for key, value in test_dict.items():
if isinstance(value, Mapping):
yield from total_keys(value)
yield len(test_dict)
# Initialize dictionary
test_dict = { 'gfg' : { 'is' : 1, 'best' : { 'for' : {'geeks' :4}}}}
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Using yield() + recursion
# Get total keys in dictionary
res = sum(total_keys(test_dict))
# printing result
print("Number of keys in dictionary is : " + str(res))
输出 :
The original dictionary is : {‘gfg’: {‘best’: {‘for’: {‘geeks’: 4}}, ‘is’: 1}}
Number of keys in dictionary is : 5