 Open in App
Not now

# Python | Sort a Dictionary

• Difficulty Level : Medium
• Last Updated : 17 Mar, 2023

Python, Given a dictionary, perform sort, basis on keys or values. [ applicable Python >=3.6v ].

Input : test_dict = {“Gfg” : 5, “is” : 7, “Best” : 2} Output : {‘Best’: 2, ‘Gfg’: 5, ‘is’: 7}, {‘is’: 7, ‘Gfg’: 5, ‘Best’: 2} Explanation : Sorted by keys, in ascending and reverse order. Input : test_dict = {“Best” : 2, “for” : 9, “geeks” : 8} Output : {‘Best’: 2, ‘Gfg’: 5, ‘for’: 9}, {‘for’: 9, ‘geeks’: 8, ‘Best’: 2} Explanation : Sorted by values, in ascending and reverse order.

Case 1 : Sort by Keys

This task is performed using sorted(), in this, we extract the keys using 1st index of items of dictionary extracted by items(), and pass it in key as custom lambda function to get sorted by keys. The “reverse=True” is added to perform reverse sort.

## Python3

 `# Python3 code to demonstrate working of ` `# Sort a Dictionary` `# Sort by Keys`   `# initializing dictionary` `test_dict ``=` `{``"Gfg"` `: ``5``, ``"is"` `: ``7``, ``"Best"` `: ``2``, ``"for"` `: ``9``, ``"geeks"` `: ``8``}`   `# printing original dictionary` `print``(``"The original dictionary is : "` `+` `str``(test_dict))`   `# using items() to get all items ` `# lambda function is passed in key to perform sort by key ` `res ``=` `{key: val ``for` `key, val ``in` `sorted``(test_dict.items(), key ``=` `lambda` `ele: ele[``0``])}`   `# printing result ` `print``(``"Result dictionary sorted by keys : "` `+` `str``(res)) `   `# using items() to get all items ` `# lambda function is passed in key to perform sort by key ` `# adding "reversed = True" for reversed order` `res ``=` `{key: val ``for` `key, val ``in` `sorted``(test_dict.items(), key ``=` `lambda` `ele: ele[``0``], reverse ``=` `True``)}`   `# printing result ` `print``(``"Result dictionary sorted by keys ( in reversed order ) : "` `+` `str``(res)) `

Output

```The original dictionary is : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8}
Result dictionary sorted by keys : {'Best': 2, 'Gfg': 5, 'for': 9, 'geeks': 8, 'is': 7}
Result dictionary sorted by keys ( in reversed order ) : {'is': 7, 'geeks': 8, 'for': 9, 'Gfg': 5, 'Best': 2}```

Case 2 : Sort by Values

This task can be performed in similar way as above, the only difference being for extracting values, 2nd element of items() is passed as comparator.

## Python3

 `# Python3 code to demonstrate working of ` `# Sort a Dictionary` `# Sort by Values `   `# initializing dictionary` `test_dict ``=` `{``"Gfg"` `: ``5``, ``"is"` `: ``7``, ``"Best"` `: ``2``, ``"for"` `: ``9``, ``"geeks"` `: ``8``}`   `# printing original dictionary` `print``(``"The original dictionary is : "` `+` `str``(test_dict))`   `# using items() to get all items ` `# lambda function is passed in key to perform sort by key ` `# passing 2nd element of items()` `res ``=` `{key: val ``for` `key, val ``in` `sorted``(test_dict.items(), key ``=` `lambda` `ele: ele[``1``])}`   `# printing result ` `print``(``"Result dictionary sorted by values : "` `+` `str``(res)) `   `# using items() to get all items ` `# lambda function is passed in key to perform sort by key ` `# passing 2nd element of items()` `# adding "reversed = True" for reversed order` `res ``=` `{key: val ``for` `key, val ``in` `sorted``(test_dict.items(), key ``=` `lambda` `ele: ele[``1``], reverse ``=` `True``)}`   `# printing result ` `print``(``"Result dictionary sorted by values ( in reversed order ) : "` `+` `str``(res))`

Output

```The original dictionary is : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8}
Result dictionary sorted by values : {'Best': 2, 'Gfg': 5, 'is': 7, 'geeks': 8, 'for': 9}
Result dictionary sorted by values ( in reversed order ) : {'for': 9, 'geeks': 8, 'is': 7, 'Gfg': 5, 'Best': 2}```

#### Approach

this approach uses the sorted() function to sort a dictionary by its values in either ascending or descending order. The sorted() function is called with the items() method of the dictionary and a key function that returns the second element of each tuple (i.e., the values) or their negation. The resulting list of tuples is passed to the OrderedDict() constructor to create a new ordered dictionary with the same key-value pairs as the original dictionary but sorted by value.

#### Algorithm

1. Call the sorted() function on the dictionary ‘test_dict’, passing a lambda function as the ‘key’ argument.
2. The lambda function takes each key-value pair as input and returns the key or value to sort by, depending on the desired order.
3. Use the sorted() function to return a list of sorted key-value pairs.
4. Pass the sorted list to the OrderedDict() constructor to create a new ordered dictionary.
5. Return the ordered dictionary.

## Python3

 `from` `collections ``import` `OrderedDict` `from` `operator ``import` `itemgetter`   `def` `sort_dict_by_value(test_dict):` `    ``sorted_list ``=` `sorted``(test_dict.items(), key``=``itemgetter(``1``))` `    ``return` `OrderedDict(sorted_list)`   `def` `sort_dict_by_value_reverse(test_dict):` `    ``sorted_list ``=` `sorted``(test_dict.items(), key``=``itemgetter(``1``), reverse``=``True``)` `    ``return` `OrderedDict(sorted_list)`   `test_dict ``=` `{``"Gfg"` `: ``5``, ``"is"` `: ``7``, ``"Best"` `: ``2``, ``"for"` `: ``9``, ``"geeks"` `: ``8``}` `print``(sort_dict_by_value(test_dict))` `print``(sort_dict_by_value_reverse(test_dict))`

Output

```OrderedDict([('Best', 2), ('Gfg', 5), ('is', 7), ('geeks', 8), ('for', 9)])
OrderedDict([('for', 9), ('geeks', 8), ('is', 7), ('Gfg', 5), ('Best', 2)])
```

Time Complexity: O(N log N), where N is the number of key-value pairs in the dictionary.
Space Complexity: O(N), as we are creating a new ordered dictionary to store the sorted key-value pairs.

My Personal Notes arrow_drop_up
Related Articles