Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

sorting
dictionary
python

How to sort a dictionary in Python

Educative Answers Team

A dictionary in Python is a data structure which stores values as a key-value pair. We can sort this type of data by either the key or the value and this is done by using the sorted() function.

First, we need to know how to retrieve data from a dictionary to be passed on to this function.


Retrieving data

There are two basic ways to get data from a dictionary:

  1. Dictionary.keys() : Returns only the keys in an arbitrary order.
  2. Dictionary.values() : Returns a list of values.
  3. Dictionary.items() : Returns all of the data as a list of key-value pairs.

Sorted() syntax

This method takes one mandatory and two optional arguments:

  1. Data (mandatory): The data to be sorted. We will pass the data we retrieved using one of the above methods.
  2. Key (optional): A function (or criteria) based on which we would like to sort the list. For example, the criteria could be sorting strings based on their length, or any other arbitrary function. This function is applied to every element of the list and the resulting data is sorted. Leaving it empty will sort the list based on its original values.
  3. Reverse (optional): Setting the third parameter as true will sort the list in descending order. Leaving this empty sorts in ascending order.
svg viewer
Using the Sorted() method

Examples

Depending on the data we pass on to the sorted() function, we have three different ways to sort a Dictionary in Python.

dict = {}
dict['1'] = 'apple'
dict['3'] = 'orange'
dict['2'] = 'pango'

lst = dict.keys()

# Sorted by key
print("Sorted by key: ", sorted(lst))

RELATED TAGS

sorting
dictionary
python
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring