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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance
  • Going All In On the JVM 25 Virtual Threads
  • Who Should Grade Your AI? Rules vs LLM Judges vs Humans
  • Replay, Scheduling, and Throttling: Engineering a Self-Service Kafka Streaming Tool at Scale

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Jun. 28, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
153.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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. 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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook