VOOZH about

URL: https://www.analyticsvidhya.com/blog/2024/01/easy-ways-to-sort-a-dictionary-in-python/

⇱ 5 Ways to Sort a Dictionary in Python: Analytics Vidhya


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

5 Easy Ways to Sort a Dictionary in Python

Pankaj Singh Last Updated : 11 Jan, 2024
4 min read

Introduction

Sorting a dictionary in Python can be tricky, especially for beginners. Python dictionaries are versatile and powerful data structures that allow you to store and retrieve key-value pairs efficiently. They provide a flexible way to represent and manipulate data, offering dynamic resizing, quick lookup, and support for a wide range of data types as both keys and values. 

With features like essential uniqueness and the ability to iterate over items, Python dictionaries are crucial components in various programming tasks, from managing configurations to organizing complex data structures. Their ease of use and extensive functionality make them a cornerstone in Python programming, facilitating tasks ranging from data processing to algorithm implementation. However, there are several easy and efficient ways to achieve this. In this article, we will explore 5 different methods to sort a dictionary in Python, along with their pros and cons.

Using the Sorted() Function

The sorted() function is a versatile tool that can be used to sort a dictionary in Python based on its keys or values. This method is simple and effective, making it a popular choice among Python developers. Here’s a simple example of how to use the sorted() function to sort a dictionary by its keys:

Example

# Sample code for sorting a dictionary by keys using the sorted() function

marks = {'Tarun': 98, 'Himanshu': 90, 'Harshit': 95}

sorted_dict = {k: marks[k] for k in sorted(marks)}

print(sorted_dict)

Output

{‘Harshit’: 95, ‘Himanshu’: 90, ‘Tarun’: 98}

Using the Itemgetter() Function

The itemgetter() function from the operator module can be used to sort a dictionary in Python by its values. This method provides a more flexible approach to sorting, allowing developers to customize the sorting criteria based on their specific requirements. Here’s an example of how to use the itemgetter() function to sort a dictionary by its values:

Example

# Sample code for sorting a dictionary by values using the itemgetter() function

import operator

marks = {'Tarun': 98, 'Himanshu': 90, 'Harshit': 95}

sorted_dict = dict(sorted(marks.items(), key=operator.itemgetter(1)))

print(sorted_dict)

Output

{‘Himanshu’: 90, ‘Harshit’: 95, ‘Tarun’: 98}

Using List Comprehensions

List comprehensions offer a concise and elegant way to sort a dictionary in Python. Converting the dictionary into a list of tuples makes it easier to apply sorting operations using list comprehensions. Here’s an example of how to use list comprehensions to sort a dictionary by its keys:

Example

# Sample code for sorting a dictionary by keys using list comprehensions

marks = {'Tarun': 98, 'Himanshu': 90, 'Harshit': 95}

sorted_dict = {k: v for k, v in sorted(marks.items())}

print(sorted_dict)

Output:-

{‘Harshit’: 95, ‘Himanshu’: 90, ‘Tarun’: 98}

Using the OrderedDict Class

The OrderedDict class from the collections module can be used to create a sorted dictionary representation. This method preserves the original insertion order of the dictionary while providing a sorted view of its contents. Here’s an example of how to use the OrderedDict class to sort a dictionary by its keys:

Example

# Sample code for sorting a dictionary by keys using the OrderedDict class

from collections import OrderedDict

marks = {'Tarun': 98, 'Himanshu': 90, 'Harshit': 95}

sorted_dict = OrderedDict(sorted(marks.items()))

print(sorted_dict)

Output

OrderedDict([(‘Harshit’, 95), (‘Himanshu’, 90), (‘Tarun’, 98)])

Using the Pandas Library

For developers working with large datasets, the Pandas library offers a powerful solution for sorting dictionaries in Python. By leveraging the DataFrame data structure, Pandas provides efficient methods for sorting and manipulating dictionary-like objects. Here’s an example of how to use the Pandas library to sort a dictionary by its keys:

Example

# Sample code for sorting a dictionary by keys using the Pandas library

import pandas as pd

marks = {'Tarun': 98, 'Himanshu': 90, 'Harshit': 95}

sorted_dict = pd.DataFrame(list(marks.items()), columns=['Key', 'Value']).sort_values('Value').set_index('Key').to_dict()['Value']

print(sorted_dict)

Output

{‘Himanshu’: 90, ‘Harshit’: 95, ‘Tarun’: 98}

Tabular Comparison: Sort a Dictionary in Python

Here’s a comparison of 5 Easy Ways to Sort a Dictionary in Python in tabular format:

MethodDescriptionProsCons
Sorted() FunctionUtilizes the built-in sorted() function– Simple and easy to use– Creates a new list; may not be memory-efficient
Itemgetter() FunctionLeverages itemgetter from the operator module– Efficient for sorting based on specific keys– Requires importing the operator module
List ComprehensionsUses list comprehensions to create a new dictionary– Provides flexibility for custom sorting criteria– Requires additional syntax and understanding
OrderedDict ClassUtilizes the OrderedDict class from the collections module– Preserves insertion order– Slightly slower than regular dictionaries
Pandas LibraryEmploys the sort_values() method from the Pandas library– Ideal for handling large datasets– Adds dependency on the Pandas library

Choose the method that best suits your specific sorting requirements and the characteristics of your data.

Conclusion

In this article, we explored 5 easy and efficient ways to sort a dictionary in Python. Each method offers its advantages and can be tailored to suit different use cases. By understanding these techniques, developers can gain a deeper insight into the versatility of Python’s data manipulation capabilities. Whether it’s using built-in functions like sorted(), leveraging external libraries like Pandas, or implementing custom sorting logic, Python provides a wide array of options for sorting dictionaries.

I hope this article helped you understand how to sort a dictionary in Python. Are you ready to take your Python skills to the next level? Elevate your career with the Certified AI & ML BlackBelt Plus Program. Experience personalized learning, 1:1 mentorship, real-world projects, and top-rated guidance. Secure your future in AI/ML — Enroll Now!

Hi, I am Pankaj Singh Negi - Senior Content Editor | Passionate about storytelling and crafting compelling narratives that transform ideas into impactful content. I love reading about technology revolutionizing our lifestyle.

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
👁 Av Logo White

Continue your learning for FREE

Forgot your password?
👁 Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

👁 Popup Banner
👁 AI Popup Banner