DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Efficient String Formatting With Python f-Strings
  • Python F-Strings
  • Developing Metadata-Driven Data Engineering Pipelines Using Apache Spark and Python Dictionary
  • Python Dictionary: A Powerful Tool for Data Engineering

Trending

  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 2
  • How to Merge HTML Documents in Java
  • Understanding the Shift: Why Companies Are Migrating From MongoDB to Aerospike Database?
  • Supervised Fine-Tuning (SFT) on VLMs: From Pre-trained Checkpoints To Tuned Models
  1. DZone
  2. Coding
  3. Languages
  4. Sorting Dictionaries in Python

Sorting Dictionaries in Python

In this post, we take a look at how to sort the entries in a Python dictionary. Sometimes you just need to sort the unsorted!

By 
Jay Sridhar user avatar
Jay Sridhar
·
Jun. 28, 17 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
152.8K Views

Join the DZone community and get the full member experience.

Join For Free

1. Introduction

Dictionaries in Python are unsorted. They are stored by the hash value of the key, and this allows for fast lookup. In this article, we show a couple of ways in which dictionaries can be sorted.

2. List of Sorted Keys

Here is the sample dict that we are going to be working with:

prices = {'Apple': 1.99, 'Banana': 0.99, 'Orange': 1.49, 'Cantaloupe': 3.99, 'Grapes': 0.39}

You can obtain a sorted list of the keys using the sorted() function on the iterkeys() method.

print sorted(prices.iterkeys())

['Apple', 'Banana', 'Cantaloupe', 'Grapes', 'Orange']

Which is essentially the same as the using the sorted() function on the dict itself. This is because the sorted() function accesses the iterator of the argument, and the dictionary returns an iterator over the keys.

print sorted(prices)

['Apple', 'Banana', 'Cantaloupe', 'Grapes', 'Orange']

3. Sorting by Keys

That is all very well for obtaining a sorted list of keys, but what if we want the whole dictionary sorted in some form of a list?

Well, the method iteritems() returns an iterator of the key-value tuples of the dictionary, so you can apply the sorted() function to the return value. This returns a list of tuples sorted by the key.

print sorted(prices.iteritems())

[('Apple', 1.99), ('Banana', 0.99), ('Cantaloupe', 3.99), ('Grapes', 0.39), ('Orange', 1.49)]

4. Sorting by Values

The same method as above can be used to sort a dictionary by values in a couple of variations. First is to use the key argument to the sorted() function as follows. For each key-value tuple, we return the second item of the tuple as the sort key so the list of tuples is not sorted by the value.

print sorted(prices.iteritems(), key = lambda x : x[1])

[('Grapes', 0.39), ('Banana', 0.99), ('Orange', 1.49), ('Apple', 1.99), ('Cantaloupe', 3.99)]

And here is another method to sort a dictionary by keys. This method specifies a comparison function to the sorted() function which receives two tuples to compare and uses cmp() to compare the second element of each. This method is more general in the sense that you can specify arbitrary conditions in the comparison function.

print sorted(prices.iteritems(), lambda x, y : cmp(x[1], y[1]))

[('Grapes', 0.39), ('Banana', 0.99), ('Orange', 1.49), ('Apple', 1.99), ('Cantaloupe', 3.99)]

5. List of Sorted Values

And finally, to obtain a list of sorted values, we use the itervalues() method and pass the result to the sorted() function.

print sorted(prices.itervalues())

[0.39, 0.99, 1.49, 1.99, 3.99]

6. Reversing the Sort Order

In the all the cases above where we used the sorted() function, we can reverse the sort order merely by passing the option reverse=True.

print sorted(prices.itervalues(), reverse=True)

[3.99, 1.99, 1.49, 0.99, 0.39]

To review, we learned various aspects of sorting dictionaries. These included: obtaining a list of sorted keys and sorted values. Key-value pairs can be extracted as a list of tuples which are sorted by key or value.

Dictionary (software) Sorting Python (language)

Published at DZone with permission of Jay Sridhar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Efficient String Formatting With Python f-Strings
  • Python F-Strings
  • Developing Metadata-Driven Data Engineering Pipelines Using Apache Spark and Python Dictionary
  • Python Dictionary: A Powerful Tool for Data Engineering

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!