Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the keys of nested dictionaries and render them in sorted order. This kind of application can occur in domains in which we work with data. Lets discuss certain ways in which this task can be performed.
Method #1 : Using yield + isinstance() + loop The combination of above functions can be used to perform this task. In this, we perform the task of detection of keys using isinstance(). The yield keyword is used to add intermediate results.
Python3
def hlper_fnc(test_dict):
for key, val in test_dict.items():
yield key
if isinstance (val, dict ):
yield from val
test_dict = { 'gfg' : 43 , 'is' : { 'best' : 14 , 'for' : 35 , 'geeks' : 42 }, 'and' : { 'CS' : 29 }}
print ("The original dictionary is : " + str (test_dict))
res = sorted (hlper_fnc(test_dict))
print ("The sorted nested keys : " + str (res))
|
Output : 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’]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2 : Using sorted() + list comprehension + isinstance() The combination of above functions offer a shorthand solution to this problem. In this, the sorting is done using sorted(). The isinstance() is used to detect keys.
Python3
test_dict = { 'gfg' : 43 , 'is' : { 'best' : 14 , 'for' : 35 , 'geeks' : 42 }, 'and' : { 'CS' : 29 }}
print ("The original dictionary is : " + str (test_dict))
res = sorted ([key for val in test_dict.values() if isinstance (val, dict )
for key in val] + list (test_dict))
print ("The sorted nested keys : " + str (res))
|
Output : 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’]
Method 3 : use a recursive function
step-by-step approach:
Define a function, collect_keys, that takes a dictionary as input.
Inside the function, create an empty list to collect the keys.
Loop through each key-value pair in the dictionary.
If the value is a dictionary, call the collect_keys function recursively on the value and append the result to the list of keys.
Otherwise, append the key to the list of keys.
Sort the list of keys.
Return the list of keys.
Call the collect_keys function on the original dictionary.
Print the sorted list of keys.
Python3
test_dict = { 'gfg' : 43 , 'is' : { 'best' : 14 , 'for' : 35 , 'geeks' : 42 }, 'and' : { 'CS' : 29 }}
print ( "The original dictionary is : " + str (test_dict))
def collect_keys(dictionary):
keys = []
for key, value in dictionary.items():
if isinstance (value, dict ):
keys + = collect_keys(value)
keys.append(key)
keys.sort()
return keys
res = collect_keys(test_dict)
print ( "The sorted nested keys : " + str (res))
|
OutputThe original dictionary is : {'gfg': 43, 'is': {'best': 14, 'for': 35, 'geeks': 42}, 'and': {'CS': 29}}
The sorted nested keys : ['CS', 'and', 'best', 'for', 'geeks', 'gfg', 'is']
The time complexity of this approach is O(n log n) due to the sorting step, where n is the total number of keys in the dictionary (including nested keys).
The auxiliary space complexity is O(n) to store the list of keys.