Python - Sorted Nested Keys in Dictionary
Last Updated :
15 May, 2023
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
# 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))
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
# 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))
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
# Python3 code to demonstrate working of
# Sorted Nested Keys in Dictionary
# Using recursive function to collect keys
# 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))
# define function to collect keys recursively
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
# call collect_keys on the original dictionary
res = collect_keys(test_dict)
# printing result
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.
Similar Reads
Python | Sort nested dictionary by key Sorting has quite vivid applications and sometimes, we might come up with a problem in which we need to sort the nested dictionary by the nested key. This type of application is popular in web development as JSON format is quite popular. Let's discuss certain ways in which this can be performed. Met
4 min read
Python | Sort dictionary keys to list Sometimes, we wish to flatten the dictionary into list, the simple flattening is relatively easier, but when we wish to align keys and values in sorted way, i.e sorted by value, then it becomes quite a complex problem. Let's discuss certain ways in which this task can be performed. Method #1 : Using
4 min read
Sort a Nested Dictionary by Value in Python Sorting a nested dictionary in Python involves understanding its structure, defining sorting criteria, and utilizing the `sorted()` function or `.sort()` method with a custom sorting function, often a lambda. This process is essential for organizing complex, hierarchical data efficiently. Mastery of
3 min read
Python - Sort Dictionary ignoring Key Sometimes, while working with Python dictionaries, we can have problem in which we need to perform sorting of dictionary elements. This is quite straight forward, but sometimes, we can have certain stray keys, which we don't wish to alter order while sorting. This works for Python >= 3.6 as keys
6 min read
How to Print Dictionary Keys in Python We are given a dictionary and our task is to print its keys, this can be helpful when we want to access or display only the key part of each key-value pair. For example, if we have a dictionary like this: {'gfg': 1, 'is': 2, 'best': 3} then the output will be ['gfg', 'is', 'best']. Below, are the me
2 min read
Python Sort Nested Dictionary by Multiple Values We are given a nested dictionary and our task is to sort a nested dictionary by multiple values in Python and print the result. In this article, we will see how to sort a nested dictionary by multiple values in Python. Example: Input : {'A': {'score': 85, 'age': 25}, 'B': {'score': 92, 'age': 30}, '
3 min read
Python - Sort Dictionary key and values List Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the sorting of it, wrt keys, but also can have a variation in which we need to perform a sort on its values list as well. Let's discuss certain way in which this task can be performed. Input : test_d
6 min read
Loop Through a Nested Dictionary in Python Working with nested dictionaries in Python can be a common scenario, especially when dealing with complex data structures. Iterating through a nested dictionary efficiently is crucial for extracting and manipulating the desired information. In this article, we will explore five simple and generally
3 min read
Python - Sort Nested keys by Value Sometimes, while working with data records, we can have a problem in which we need to perform the sorting of nested keys of dictionary by the value of occurrence. This can have applications in arranging scores, prices etc. Lets discuss a way in which this task can be performed. Method #1 : Using sor
3 min read