Python program to sort Dictionary by Key Lengths
Last Updated :
02 May, 2023
Given Dictionary, sort by its key lengths.
Input : test_dict = {"Gfg" : 4, "is" : 1, "best" : 0, "for" : 3, "geeks" : 3}
Output : {'is': 1, 'Gfg': 4, 'for': 3, 'best': 0, 'geeks': 3}
Explanation : 2 < 3 = 3 < 4 < 5, are sorted lengths in order.
Input : test_dict = {"Gfg" : 4, "for" : 3, "geeks" : 3}
Output : {'Gfg': 4, 'for': 3, 'geeks': 3}
Explanation : 3 = 3 < 5, are sorted lengths in order.
Method #1 : Using len() + sort() + dictionary comprehension + items()
In this, we perform the task of sorting using sort(), items() is used to get tuple pair from the dictionary, len() gets the keys lengths. Then dictionary comprehension performs the task of converting back to dictionary.
Python3
# Python3 code to demonstrate working of
# Sort Dictionary by Key Lengths
# Using len() + sort() + dictionary comprehension + items()
def get_len(key):
return len(key[0])
# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 1, "best" : 0, "for" : 3, "geeks" : 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorting using sort()
# external to render logic
test_dict_list = list(test_dict.items())
test_dict_list.sort(key = get_len)
# reordering to dictionary
res = {ele[0] : ele[1] for ele in test_dict_list}
# printing result
print("The sorted dictionary : " + str(res))
Output:
The original dictionary is : {'Gfg': 4, 'is': 1, 'best': 0, 'for': 3, 'geeks': 3} The sorted dictionary : {'is': 1, 'Gfg': 4, 'for': 3, 'best': 0, 'geeks': 3}
Time complexity: O(n*logn)
Space complexity: O(1)
Method #2 : Using sorted() + lambda function + items() + dictionary comprehension
In this, we perform the task of sorting using sorted(), lambda function is used to provide the logic of getting key lengths.
Python3
# Python3 code to demonstrate working of
# Sort Dictionary by Key Lengths
# Using sorted() + lambda function + items() + dictionary comprehension
# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 1, "best" : 0, "for" : 3, "geeks" : 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorting using sorted()
# lambda fnc. to render logic
test_dict_list = sorted(list(test_dict.items()), key = lambda key : len(key[0]))
# reordering to dictionary
res = {ele[0] : ele[1] for ele in test_dict_list}
# printing result
print("The sorted dictionary : " + str(res))
Output:
The original dictionary is : {'Gfg': 4, 'is': 1, 'best': 0, 'for': 3, 'geeks': 3} The sorted dictionary : {'is': 1, 'Gfg': 4, 'for': 3, 'best': 0, 'geeks': 3}
Method #5: Using zip() + sorted() + dictionary constructor
First, a dictionary called test_dict is initialized with 5 key-value pairs, where each key is a string and each value is an integer.
The original dictionary is printed using the print() function and the concatenation operator + to join the string "The original dictionary is : " and the string representation of the test_dict dictionary obtained using the str() function.
The sorted() function is used to sort the keys of the test_dict dictionary by their length in ascending order. The sorted keys are assigned to the variable sorted_keys.
The zip() function is used to create a new iterable where each element is a tuple consisting of a key from the sorted_keys list and the corresponding value from the test_dict dictionary.
The list comprehension [test_dict[key] for key in sorted_keys] is used to create a list of values corresponding to the keys in the sorted_keys list, in the order specified by sorted_keys.
The dict() function is used to create a new dictionary from the tuples generated by the zip() function. This new dictionary is assigned to the variable sorted_dict.
The sorted dictionary is printed using the print() function and the concatenation operator + to join the string "The sorted dictionary : " and the string representation of the sorted_dict dictionary obtained using the str() function.
Python3
# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 1, "best" : 0, "for" : 3, "geeks" : 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorting dictionary by key lengths using zip() and sorted()
sorted_keys = sorted(test_dict.keys(), key=len)
sorted_dict = dict(zip(sorted_keys, [test_dict[key] for key in sorted_keys]))
# printing result
print("The sorted dictionary : " + str(sorted_dict))
OutputThe original dictionary is : {'Gfg': 4, 'is': 1, 'best': 0, 'for': 3, 'geeks': 3}
The sorted dictionary : {'is': 1, 'Gfg': 4, 'for': 3, 'best': 0, 'geeks': 3}
Time complexity: O(n*log(n)), where n is the number of items in the dictionary.
Auxiliary space: O(n), where n is the number of items in the dictionary.
Similar Reads
Python - Sort dictionary by Tuple Key Product
Given dictionary with tuple keys, sort dictionary items by tuple product of keys. Input : test_dict = {(2, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12} Output : {(2, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12} Explanation : 6 < 18 < 32 < 40, key products hence retains order. Input : test_d
5 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
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 by value list length
While working with Python, one might come to a problem in which one needs to perform a sort on dictionary list value length. This can be typically in case of scoring or any type of count algorithm. Let's discuss a method by which this task can be performed. Method 1: Using sorted() + join() + lambda
4 min read
Python - Keys with shortest length lists in dictionary
Sometimes, while working with Python lists, we can have problem in which we need to return the keys which have minimum lengths of lists as values. This can have application in domains in which we work with data. Lets discuss certain ways in which this task can be performed. Method #1: Using len() +
4 min read
Python program to Swap Keys and Values in Dictionary
Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value so that they can be retrieved efficiently. Letâs discuss various ways of swapping the keys and values in Python Dictionary. Method#1 (Does not work when there are multiple same values
4 min read
Output of Python Program - Dictionary (set 25)
Prerequisite: Dictionaries in PythonThese question sets will make you conversant with Dictionary Concepts in Python programming language. Â Question 1: Which of the following is true about Python dictionaries? A. Items are accessed by their position in a dictionary. B. All the keys in a dictionary m
3 min read
Python - Sort Dictionary by Values and Keys
Given a dictionary, sort according to descended values, if similar values, then by keys lexicographically. Input : test_dict = {"gfg" : 1, "is" : 1, "best" : 1, "for" : 1, "geeks" : 1} Output : {"best" : 1, "is" : 1, "for" : 1, "geeks" : 1, "gfg" : 1} Explanation : All values are equal, hence lexico
3 min read
Sort List of Dictionaries by Multiple Keys - Python
We are given a list of dictionaries where each dictionary contains various keys and our task is to sort the list by multiple keys. Sorting can be done using different methods such as using the sorted() function, a list of tuples, itemgetter() from the operator module. For example, if we have the fol
3 min read
Output of Python Programs | Set 24 (Dictionary)
Prerequisite : Python-Dictionary1. What will be the output?Python dictionary = {"geek":10, "for":45, "geeks": 90} print("geek" in dictionary) Options: 10FalseTrueErrorOutput:3. TrueExplanation: in is used to check the key exist in dictionary or not. 2. What will be the output?Python dictionary ={1:"
2 min read