VOOZH about

URL: https://www.analyticsvidhya.com/blog/2024/03/how-to-sort-python-dictionaries-by-key-or-value/

⇱ How to Sort Python Dictionaries by Key or Value


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

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

How to Sort Python Dictionaries by Key or Value

NISHANT TIWARI Last Updated : 07 Mar, 2024
5 min read

Introduction

Python dictionaries are an essential data structure that allows you to store and retrieve key-value pairs efficiently. However, there may be instances where you need to sort the dictionary based on either the keys or the values. In this article, we will explore various techniques to sort Python dictionaries by key or value, along with their performance comparison and pros and cons.

What is a Python Dictionary?

A Python dictionary is an unordered collection of key-value pairs. It is implemented as a hash table, which provides fast access to values based on their keys. Dictionaries are mutable and can store values of different data types. To access a value in a dictionary, you need to provide its corresponding key.

Importance of Sorting Python Dictionaries

Sorting dictionaries can be useful in scenarios where you want to retrieve the data in a specific order. For example, if you have a dictionary containing student names as keys and their corresponding scores as values, sorting the dictionary by scores can help you identify the top-performing students easily. Sorting dictionaries also allows you to perform operations like finding the minimum or maximum value, filtering data based on certain criteria, or displaying data in a more organized manner.

Sorting Python Dictionaries by Key

There are several techniques to sort Python dictionaries by key. Let’s explore them one by one.

Using the sorted() Function

The sorted() function in Python returns a new list containing all items from the original dictionary, sorted in ascending order by key. Here’s an example:

Code:

student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.items())
print(sorted_scores)

Output:

[('Aayush', 85), ('DeepSandhya', 92), ('Himanshu', 78), ('Nishant', 95)]

Using the keys() Method

The keys() method returns a view object that contains the keys of the dictionary. By converting this view object into a list and sorting it, we can achieve the desired result. Here’s an example:

Code:

student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.keys())
print(sorted_scores)

Output:

['Aayush', 'DeepSandhya', 'Himanshu', 'Nishant']

Using the operator.itemgetter() Function

The operator.itemgetter() function allows us to specify the key based on which we want to sort the dictionary. Here’s an example:

Code:

import operator
student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.items(), key=operator.itemgetter(0))
print(sorted_scores)

Output:

[('Aayush', 85), ('DeepSandhya', 92), ('Himanshu', 78), ('Nishant', 95)]

Using a Lambda Function

Lambda functions are anonymous functions that can be used to define simple functions in a single line. We can use a lambda function to specify the key based on which we want to sort the dictionary. Here’s an example:

Code:

student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.items(), key=lambda x: x[0])
print(sorted_scores)

Output:

[('Aayush', 85), ('DeepSandhya', 92), ('Himanshu', 78), ('Nishant', 95)]

Sorting Python Dictionaries by Value

Similar to sorting by key, we can also sort Python dictionaries by value. Let’s explore the techniques for sorting dictionaries by value.

Using the sorted() Function with a Custom Key

We can use the sorted() function with a custom key to sort the dictionary by value. Here’s an example:

Code:

student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.items(), key=lambda x: x[1])
print(sorted_scores)

Output:

[('Himanshu', 78), ('Aayush', 85), ('DeepSandhya', 92), ('Nishant', 95)]

Using the operator.itemgetter() Function

Similar to sorting by key, we can use the operator.itemgetter() function to specify the key based on which we want to sort the dictionary. Here’s an example:

Code:

import operator
student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.items(), key=operator.itemgetter(1))
print(sorted_scores)

Output:

[('Himanshu', 78), ('Aayush', 85), ('DeepSandhya', 92), ('Nishant', 95)]

Using a Lambda Function

We can also use a lambda function to specify the key based on which we want to sort the dictionary. Here’s an example:

Code:

student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.items(), key=lambda x: x[1])
print(sorted_scores)

Output:

[('Himanshu', 78), ('Aayush', 85), ('DeepSandhya', 92), ('Nishant', 95)]

Comparing Different Sorting Techniques

Now that we have explored various techniques to sort Python dictionaries by key or value, let’s compare their performance and discuss their pros and cons.

Performance Comparison

The performance of different sorting techniques can vary based on the size of the dictionary and the specific requirements of the sorting operation. However, in general, the sorted() function with a custom key or a lambda function tends to be more efficient than using the keys() method or the operator.itemgetter() function. This is because the sorted() function internally uses the Timsort algorithm, which has a time complexity of O(n log n).

Pros and Cons of Each Technique

  • Using the sorted() function: This technique is simple and versatile, allowing you to sort dictionaries by key or value with ease. However, it may not be the most efficient option for large dictionaries.
  • Using the keys() method: This technique is straightforward and can be useful if you only need to sort the keys. However, it requires converting the view object into a list, which can consume additional memory.
  • Using the operator.itemgetter() function: This technique provides a concise way to specify the key for sorting. However, it requires importing the operator module and may not be as intuitive for beginners.
  • Using a lambda function: This technique allows you to define the sorting key inline, making it convenient for simple sorting operations. However, it may not be suitable for complex sorting requirements.

Additional Sorting Options

Apart from sorting dictionaries by key or value, there are a few additional sorting options worth exploring.

Sorting in Reverse Order

To sort a dictionary in reverse order, you can pass the `reverse=True` argument to the sorted() function. Here’s an example:

Code:

student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.items(), key=lambda x: x[1], reverse=True)
print(sorted_scores)

Output:

[('Nishant', 95), ('DeepSandhya', 92), ('Aayush', 85), ('Himanshu', 78)]

Sorting by Multiple Keys

If you have a dictionary with multiple keys, you can sort it based on multiple criteria. Here’s an example:

Code:

student_scores = {'Aayush': {'Math': 85, 'Science': 90}, ‘Deepsandhya’: {'Math': 92, 'Science': 88}, 'Himanshu': {'Math': 78, 'Science': 95}}
sorted_scores = sorted(student_scores.items(), key=lambda x: (x[1]['Math'], x[1]['Science']))
print(sorted_scores)

Output:

[('Himanshu', {'Math': 78, 'Science': 95}), ('Aayush', {'Math': 85, 'Science': 90}), ('Deepsandhya', {'Math': 92, 'Science': 88})]

Conclusion

Sorting Python dictionaries by key or value is a common requirement in many applications. In this article, we explored various techniques to achieve this, including using the sorted() function, the keys() method, and the operator.itemgetter() function, and lambda functions. We also discussed their performance comparison and pros and cons. Additionally, we explored sorting dictionaries in reverse order and by multiple keys. By understanding these techniques, you can effectively sort dictionaries in Python based on your specific requirements.

Seasoned AI enthusiast with a deep passion for the ever-evolving world of artificial intelligence. With a sharp eye for detail and a knack for translating complex concepts into accessible language, we are at the forefront of AI updates for you. Having covered AI breakthroughs, new LLM model launches, and expert opinions, we deliver insightful and engaging content that keeps readers informed and intrigued. With a finger on the pulse of AI research and innovation, we bring a fresh perspective to the dynamic field, allowing readers to stay up-to-date on the latest developments.

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