Sort Python Dictionary by Key or Value - Python
Last Updated :
14 Oct, 2024
There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python.
Sorting Dictionary By Key Using sort()
In this example, we will sort the dictionary by keys and the result type will be a dictionary.
Python
d = {'ravi': 10, 'rajnish': 9, 'sanjeev': 15}
myKeys = list(d.keys())
myKeys.sort()
# Sorted Dictionary
sd = {i: d[i] for i in myKeys}
print(sd)
Output{'rajnish': 9, 'ravi': 10, 'sanjeev': 15}
Displaying the Keys in Sorted Order using sorted() on Keys
In this example, we are trying to sort the dictionary by keys and values in Python. Here, keys() returns an iterator over the dictionary’s keys.
Python
# Initializing key-value pairs
d = {2: 56, 1: 2, 5: 12, 4: 24}
print("Dictionary", d)
# Sorting and printing dictionary keys
for i in sorted(d.keys()):
print(i, end=" ")
OutputDictionary {2: 56, 1: 2, 5: 12, 4: 24}
1 2 4 5
Sorting the dictionary by key using OrderedDict
In this example, we will sort in lexicographical order Taking the key's type as a string.
Python
# Creates a sorted dictionary (sorted by key)
from collections import OrderedDict
d = {'ravi': '10', 'rajnish': '9', 'abc': '15'}
d1 = OrderedDict(sorted(d.items()))
print(d1)
OutputOrderedDict([('abc', '15'), ('rajnish', '9'), ('ravi', '10')])
Sorting the Keys Alphabetically Using Sorted on Dictionary
When we use sorted on a dictionary, it sorts by keys by default.
Python
# Initializing key-value pairs
d = {2: 56, 1: 2, 3: 323}
print("Dictionary", d)
# Sorting and printing key-value pairs by the key
for i in sorted(d):
print((i, d[i]), end=" ")
OutputDictionary {2: 56, 1: 2, 3: 323}
(1, 2) (2, 56) (3, 323)
Sorting Alphabetically by Values using Sorted
In this example, we are trying to sort the dictionary by keys and values in Python. Here we are using to sort in lexicographical order.
Python
# Initializing the key-value pairs
d = {2: 56, 100: 2, 3: 323}
print("Dictionary", d)
# Sorting key-value pairs by value, and by key if values are the same
sorted_items = sorted(d.items(), key=lambda kv: (kv[1], kv[0]))
print(sorted_items)
OutputDictionary {2: 56, 100: 2, 3: 323}
[(100, 2), (2, 56), (3, 323)]
Sorting Dictionary By Value using Numpy
In this example, we are trying to sort the dictionary by values in Python. Here we are using dictionary comprehension to sort our values.
Python
# Creates a sorted dictionary (sorted by key)
from collections import OrderedDict
import numpy as np
d = {'ravi': 10, 'rajnish': 9,
'sanjeev': 15, 'yash': 2, 'suraj': 32}
print(d)
keys = list(d.keys())
values = list(d.values())
sorted_value_index = np.argsort(values)
sorted_dict = {keys[i]: values[i] for i in sorted_value_index}
print(sorted_dict)
Output{'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32}
{'yash': 2, 'rajnish': 9, 'ravi': 10, 'sanjeev': 15, 'suraj': 32}
Sorting Dictionary By Value using sorted() method
In the below given example, the dictionary is sorted using a 'lambda' to obtain the desired result of sorting the dictionary based on values.
Python
# Key, Value of the dictionary defined
d = {'watermelon': 1, 'apple': 2, 'banana': 3}
# Sort based on Values
val_based = {k: v for k, v in sorted(d.items(), key=lambda item: item[1])}
# item[1] represents the sorting based on value
# Sort based on reverse of Values
val_based_rev = {k: v for k, v in sorted(d.items(), key=lambda item: item[1], reverse=True)}
# Print sorted dictionary
print(val_based)
print(val_based_rev)
Output{'watermelon': 1, 'apple': 2, 'banana': 3}
{'banana': 3, 'apple': 2, 'watermelon': 1}
Need for Sorting Dictionary in Python
We need sorting of data to reduce the complexity of the data and make queries faster and more efficient. Sorting is very important when we are dealing with a large amount of data.
We can sort a dictionary by values using these methods:
- First, sort the keys alphabetically using key_value.iterkeys() function.
- Second, sort the keys alphabetically using the sorted (key_value) function & print the value corresponding to it.
- Third, sort the values alphabetically using key_value.iteritems(), key = lambda (k, v) : (v, k))
We have covered different examples based on sorting dictionary by key or value. Reading and practicing these Python codes will help you understand sorting in Python dictionaries.
You can easily sort the values of dictionaries by their key or value.
Similar Reads:
Similar Reads
Get Key from Value in Dictionary - Python The goal is to find the keys that correspond to a particular value. Since dictionaries quickly retrieve values based on keys, there isn't a direct way to look up a key from a value. Using next() with a Generator ExpressionThis is the most efficient when we only need the first matching key. This meth
5 min read
Ways to sort list of dictionaries by values in Python â Using itemgetter In this article, we will cover how to sort a dictionary by value in Python. To sort a list of dictionaries by the value of the specific key in Python we will use the following method in this article.In everyday programming, sorting has always been a helpful tool. Python's dictionary is frequently ut
2 min read
Python | Pandas Index.sort_values() Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.sort_values() function is used to sort the index values. The function ret
2 min read
Python | Sort the list alphabetically in a dictionary In Python Dictionary is quite a useful data structure, which is usually used to hash a particular key with value, so that they can be retrieved efficiently. Let's see how to sort the list alphabetically in a dictionary. Sort a List Alphabetically in PythonIn Python, Sorting a List Alphabetically is
3 min read
Python | Sort Tuples in Increasing Order by any key Given a tuple, sort the list of tuples in increasing order by any key in tuple. Examples: Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)] m = 0 Output : [(1, 2), (2, 3), (2, 5), (4, 4)] Explanation: Sorted using the 0th index key. Input : [(23, 45, 20), (25, 44, 39), (89, 40, 23)] m = 2 Output : So
3 min read
Python - Keys associated with value list in dictionary Sometimes, while working with Python dictionaries, we can have a problem finding the key of a particular value in the value list. This problem is quite common and can have applications in many domains. Let us discuss certain ways in which we can Get Keys associated with Values in the Dictionary in P
4 min read
How to Sort a Set of Values in Python? Sorting means arranging the set of values in either an increasing or decreasing manner. There are various methods to sort values in Python. We can store a set or group of values using various data structures such as list, tuples, dictionaries which depends on the data we are storing. We can sort val
7 min read
Ways to sort list of dictionaries by values in Python - Using lambda function In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge
2 min read
How to Create a Dictionary in Python The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For exa
3 min read
How to Alphabetize a Dictionary in Python Alphabetizing a dictionary in Python can be useful for various applications, such as data organization and reporting. In this article, we will explore different methods to alphabetize a dictionary by its keys or values.Dictionary OrderingIn Python, dictionaries are a powerful data structure that all
2 min read