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
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
TCP/IP Model The TCP/IP model is a framework that is used to model the communication in a network. It is mainly a collection of network protocols and organization of these protocols in different layers for modeling the network.It has four layers, Application, Transport, Network/Internet and Network Access.While
7 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Basics of Computer Networking A computer network is a collection of interconnected devices that share resources and information. These devices can include computers, servers, printers, and other hardware. Networks allow for the efficient exchange of data, enabling various applications such as email, file sharing, and internet br
14 min read
Support Vector Machine (SVM) Algorithm Support Vector Machine (SVM) is a supervised machine learning algorithm used for classification and regression tasks. It tries to find the best boundary known as hyperplane that separates different classes in the data. It is useful when you want to do binary classification like spam vs. not spam or
9 min read