Python – 字典中的排序嵌套键
有时,在使用Python字典时,我们可能会遇到需要提取嵌套字典的所有键并按排序顺序呈现它们的问题。这种应用程序可以发生在我们处理数据的领域。让我们讨论可以执行此任务的某些方式。
方法 #1:使用 yield + isinstance() + 循环
上述功能的组合可用于执行此任务。在此,我们使用 isinstance() 执行密钥检测任务。 yield 关键字用于添加中间结果。
# Python3 code to demonstrate working of
# Sorted Nested Keys in Dictionary
# Using yield + isinstance() + loop
def hlper_fnc(test_dict):
for key, val in test_dict.items():
yield key
if isinstance(val, dict):
yield from val
# initializing dictionary
test_dict = {'gfg': 43, 'is': {'best' : 14, 'for' : 35, 'geeks' : 42}, 'and' : {'CS' : 29}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Sorted Nested Keys in Dictionary
# Using yield + isinstance() + loop
res = sorted(hlper_fnc(test_dict))
# printing result
print("The sorted nested keys : " + str(res))
The original dictionary is : {‘and’: {‘CS’: 29}, ‘gfg’: 43, ‘is’: {‘for’: 35, ‘best’: 14, ‘geeks’: 42}}
The sorted nested keys : [‘CS’, ‘and’, ‘best’, ‘for’, ‘geeks’, ‘gfg’, ‘is’]
方法 #2:使用sorted() + list comprehension + isinstance()
上述函数的组合为这个问题提供了一个简写的解决方案。在这种情况下,排序是使用 sorted() 完成的。 isinstance() 用于检测键。
# Python3 code to demonstrate working of
# Sorted Nested Keys in Dictionary
# Using sorted() + list comprehension + isinstance()
# initializing dictionary
test_dict = {'gfg': 43, 'is': {'best' : 14, 'for' : 35, 'geeks' : 42}, 'and' : {'CS' : 29}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Sorted Nested Keys in Dictionary
# Using sorted() + list comprehension + isinstance()
res = sorted([key for val in test_dict.values() if isinstance(val, dict)
for key in val] + list(test_dict))
# printing result
print("The sorted nested keys : " + str(res))
The original dictionary is : {‘and’: {‘CS’: 29}, ‘gfg’: 43, ‘is’: {‘for’: 35, ‘best’: 14, ‘geeks’: 42}}
The sorted nested keys : [‘CS’, ‘and’, ‘best’, ‘for’, ‘geeks’, ‘gfg’, ‘is’]