Python Dictionary sort (11 examples)

In this Python tutorial, we will discuss Python Dictionary sort. Here we will also cover the below examples:

  • Python dictionary sort by value
  • Python dictionary sort by key
  • Python dictionary sort by value descending
  • Python dictionary sort by value alphabetically
  • Python dictionary sort by key alphabetically
  • Python dictionary sort reverse
  • Python dictionary sort by key value
  • Python dictionary sort with lambda
  • Python dictionary sort by alphabetically
  • Python dictionary sort by value list
  • Python sort dictionary by value then key

Python dictionary sort

  • In Python sorted() is the built-in function that can be helpful to sort all the iterables in Python dictionary.
  • To sort the values and keys we can use the sorted() function. This sorted function will return a new list.

Syntax:

Here is the Syntax of the sorted() function.

sorted
      (
       iterable,
       Key=None,
       reverse=False
      )
  • It consists of few parameters
    • iterable: This function can be used on all iterables in a ascending order.
    • Key: If you want to modify the sorting process then you can use this key function by default its value will be none.
    • reverse: Here you can see reverse=False. It is for ascending order and if you want numbers in the descending order then you can set this reverse flag order as true
  • Note: If you decide that you are not using the optional parameter key and reverse. Python will automatically sort the items in ascending order.

Example:

Let’s take an example to check how to sort dictionaries in Python

dict = {6:'George' ,2:'John' ,1:'Potter' ,9:'Micheal' ,7:'Robert' ,8:'Gayle' }  
 
b = sorted(dict.keys())
print("Sorted keys",b)  
  
c = sorted(dict.items())
print("Sorted Values",c)  

After writing the above code, we have to sort both values and keys available in the dictionary. In python, offers built-in functions keys() and items() to sort the dictionary. We can apply these function iterable as an argument and returns a new sorted list.

Here is the Screenshot of the following given code

Python dictionary sort
Python dictionary sort

This is how to sort the dictionary in Python.

Read Python dictionary append with examples

Check Python dictionary sort – Another approach

Suppose we have a dictionary in Python that contains the elements on our fruit menu. So now we want to sort the ordered dictionary in descending order of values and keys. In this example, we have to use the reverse argument and assign them values as true.

Example:

Let’s take an example to check how to sort dictionary in Python by reverse method

dict = {"Mangoes":200,"Banana":900,"Cherry":700,"Grapes":400} 
 
new_list = sorted(dict.items(), key=lambda x: x[1], reverse=True)

for i in new_list:
	print(i[0], i[1])

Here is the Screenshot of the following given code

Python dictionary sort by reverse method
Python dictionary sort by reverse method

This is how to sort dictionary in Python.

Read How to convert dictionary to JSON in Python

Python dictionary sort by value

  • Now we can see how to sort a dictionary value in Python. By using the sorted() function you can sort the values of a dictionary.
  • In this example we can use items() and sorted() function to sort the values
  • In python dictionary there are various method to sort the values
    • Sort in Descending order
    • Sort in Ascending order

Example:

Let’s take an example and check how to sort a dictionary value in python in descending order.

dict = {"Python":750,"Java":950,"Ruby":700,"C++":200} 
 
sort_values = sorted(dict.items(), key=lambda y: y[1], reverse=True)

for i in sort_values:
	print(i[0], i[1])

Here is the Screenshot of the following given code

Python dictionary sort by value
Python dictionary sort by value

This is an example of a Python dictionary sort by value.

Python dictionary sort by value – Another example

Now we will check how to sort a dictionary by value in Python using the sorted function.

Example:

my_dict = {"Australia":250,"Germany":950,"France":170,"England":150} 
 
new_list = sorted(my_dict.items(), key=lambda x:x[1])
sort_values = dict(new_list)
print(sort_values)

In the above code, you can check that it returns a new sorted list in ascending order.

Here is the Screenshot of the following given code

Python dictionary sort by values using sorted method
Python dictionary sort by values using the sorted method

This is an example of a Python dictionary sort by value.

Read Python Concatenate Dictionary + Examples

Python Dictionary sort by key

  • Let us see how to sort a dictionary key in Python.
  • To sort dictionary key in python we can use dict.items() and sorted(iterable) method.
  • Dict.items() method returns an object that stores key-value pairs of dictionaries. The key-value pairs are contained as tuples in the object or items.
  • The sorted (iterable) method always returns the sorted list. This method sorts the no. of elements which is available in the given dictionary.

Example:

Let’s take an example and check how to sort a dictionary key in Python

my_dict = {"m":250,"o":950,"b":170,"a":150} 
 
sort_keys = my_dict.items()
new_items = sorted(sort_keys)
print(new_items)

In the above example, First, we will initialize a dictionary and assign them a key-value pair value. Then use dict.items() function to get an iterable sequence values.

Here is the Screenshot of the following given code

Python dictionary sort by key
Python dictionary sort by key

Read Python Dictionary update with examples

How to sort a dictionary keys in Python – Another approach

Using dict.keys() we can sort the dictionary keys in Python. This method returns an iterable view object that displays all the keys which is available in the dictionary.

Example:

Let’s take an example and check how to sort dictionary keys in Python

my_dict = {"p":350,"z":750,"a":170,"c":110} 
 
sorted(my_dict.keys())
for key in sorted(my_dict.keys()) :
    print(key , " : " , my_dict[key])

Here is the Screenshot of the following given code

Python dictionary sort by keys method
Python dictionary sort by keys method

This is how to sort dictionary keys in Python.

Python dictionary sort by value Descending

  • Let us see how to sort a dictionary value in descending order in Python.
  • Using dict.items() to get an iterable item that stores key-value pairs of dictionaries and call sorted(iterable, key) function that returns a new sorted list. In this case, we assign key attributes in sorted function as an argument with f as lambda key-value to sort the values.

Example:

Let’s take an example and check how to sort a dictionary value in descending order

from typing import OrderedDict


my_dict = {1: {"p":350,"z":750,"a":170,"c":110},
           6: {"p":100,"z":700,"a":120,"c":900},
           4: {"p":300,"z":200,"a":450,"c":130}}
 
sort_values = my_dict.items()
new_item = sorted(sort_values, key=lambda key_value: key_value[1]["c"], reverse=True)
list = OrderedDict(new_item)
print(list)

In the above code first, we will import an ordered dict library and create a dictionary. The key_value[1][inner_key] to sort the previous result iterable by inner key values.

Here is the Screenshot of the following given code

Python dictionary sort by value descending
Python dictionary sort by value descending

This is how to sort a Python dictionary by value Descending.

Read Python dictionary values to list

Python dictionary sort by value alphabetically

  • In Python, a dictionary is formed with key-value pair by the {key: value} method.
  • Thus, in the my_dict variable, the keys are the names, and the values are the integers to the right of the names.
  • To sort the values alphabetically you can sort and print the pairs in the dictionary that will all have the same keys.

Example:

Let’s take an example and check how to sort dictionary values alphabetically.

my_dict = {'John':2,
           'George':3,
           'Micheal':4,
           'Andrew':6,}
          

for value in sorted(my_dict.items(), key=lambda x: x[0], reverse=True):
     print(value)

Here is the Screenshot of the following given code

Python dictionary sort by value alphabetically
Python dictionary sort by value alphabetically

Python dictionary sort by key alphabetically

  • Let us see how to sort a dictionary key alphabetically in Python.
  • To sort a dictionary key alphabetically we can use dict.items() and sorted(iterable) function.
  • In this example we can use a simple algorithm to sort dictionary keys in alphabetical order, First, sort the keys using the Python sorted() function.
  • This function sorts the number of elements which is available in the given dictionary (key-value) pair.

Example:

new_dict = {"z":220,"v":450,"u":120,"t":350} 
 
sorted_keys = new_dict.items()
new_values = sorted(sorted_keys)
print(new_values)

Here is the Screenshot of the following given code

Python dictionary sort by key alphabetically
Python dictionary sort by key alphabetically

This is how to sort a Python dictionary by key alphabetically.

Read Python Check if a variable is a number

Python dictionary sort reverse

  • Let us see how to reverse the order of keys in Python dictionary.
  • The order keys are iterated in is an arbitrary element. To reverse the key-value pairs we can use dict.keys() function and looping method.

Example:

Let’s take an example and check how to reverse the order of keys

dict = {'l': 1, 'm': 2, 'n': 3}

for i in reversed(list(dict.keys())):
    print(i)

Here is the Screenshot of the following given code

Python dictionary sort reverse
Python dictionary sort reverse

This is an example of a Python dictionary sort reverse.

How to reverse the order of keys in Python dictionary

In this example, we will use the combination of dictionary functions to perform this particular task. By using list(),keys(),sorted(),reversed(). It will sort the keys and reversed gets the key extracted using dict.keys() function in descending order.

Example:

my_dict = {2 : "John", 5 : "George", 3 : "Micheal", 2 : "James"}

new_value = list(reversed(sorted(my_dict.keys())))
print(new_value)

Here is the Screenshot of the following given code

Python dictionary sort reverse keys method
Python dictionary sort reverse keys method

This is how to reverse the order of keys in a Python dictionary.

Read Check if NumPy Array is Empty in Python

Python dictionary sort by key value

  • Let us see how to sort key-value pairs using lambda function along with the item() and sorted()
  • Lambda() functions are defined without a name, that’s why it is also called as anonymous function.
  • Key-value pairs are separated by commas and enclosed with curly brackets.
  • The sorted() function is used to sort the keys of the given dictionary.

Example:

Let’s take an example and check how to sort key-value pairs in the dictionary.

my_dict = {3: 'George',
           5: 'Micheal',
           4:  'John'}
 
sort_values = sorted(
  my_dict.items(),
  key = lambda kv: kv[1]) # sort key and values

print("Sorted values and keys is :",
      sort_values)
  

Here is the Screenshot of the following given code

Python dictionary sort by key value
Python dictionary sort by key-value

This is how to sort a python dictionary by key value.

Python dictionary sort with lambda

  • Let us see how to sort a dictionary with the lambda function in Python.
  • Python lambda functions are functions that don’t have any name, they are also known as nameless functions. The word lambda is a keyword that specifies what followers are anonymous.
  • The body of the lambda function is written in a single line.
  • Due to this reason, Python lambda functions are known as throwaway functions. They are also used with the higher-order function which takes a function as an input and returned it as an output.

Example:

Let’s take an example and check how to sort a dictionary with a lambda function

my_dict = [{ "Country" : "Germany", "Val" : 40},
{ "Country" : "England", "Val" : 10 },
{ "Country" : "Japan" , "Val" : 60 }]
 

print (sorted(my_dict, key = lambda i: i['Val']))
print ("\r")
print (sorted(my_dict, key = lambda i: (i['Val'], i['Country'])))
print ("\r")
print (sorted(my_dict, key = lambda i: i['Val'],reverse=True)) # descending order

Note: For descending order use “reverse=True”

In the above example, we are using sorted() with a lambda function. First, initialize the list of dictionaries and using the sorted and lambda function to print the list sorted by the “Val” attribute. Using sorted and lambda function to print list sorted by “Val” in descending order.

Here is the Screenshot of the following given code

Python dictionary sort with lambda
Python dictionary sort with lambda

This is how to sort a Python dictionary with lambda.

Read Python remove substring from a String

Python dictionary sort by alphabetically

  • Let us see how to sort a dictionary by alphabetically in Python.
  • To sort a dictionary by alphabetically we can use sorted() and dict.items()
  • It will retuen a new list in the form of key-value pairs.

Example:

Let’s take an example and check how to sort a dictionary alphabetically

my_dict = {"k":430,"m":450,"c":420,"a":350} 
 
new_alpha = my_dict.items()
new_val = sorted(new_alpha)
print(new_val)

Here is the Screenshot of the following given code

Python dictionary sort by alphabetically
Python dictionary sort by alphabetically

This is how to sort a python dictionary alphabetically.

Python dictionary sort by value list

  • Here we will check how to sort value in the list in Python.
  • By using sorted() and dict.items() functions we will check how to sort value in the list.

Example:

my_dict = {'u': [4, 9, 2], 'v': [7, 1, 3], 'w': [5, 2, 8]}
sort_list = {l: sorted(m) for l, m in my_dict.items()} #sort value by list
print(sort_list)

Here is the Screenshot of the following given code

Python dictionary sort by value list
Python dictionary sort by value list

This is how to sort value in the list in Python.

Python sort dictionary by value then key

  • To sort a dictionary by value then the key we can easily use the lambda and sorted function.
  • In this example, we can set this reverse flag order as true which means the value will be in descending order.

Example:

Let’s take an example and check how to sort a dictionary by value than the key

dict={49:1, 52:4, 74:3, 19:6, 101:2}
z = sorted(dict.items(), key=lambda x: (x[1],x[0]), reverse=True)
print(z)

Here is the Screenshot of the following given code

Python sort dictionary by value then key
Python sort dictionary by value then key

This is how to sort a dictionary by value then key in Python.

You may like the following Python tutorials:

In this Python tutorial, we will discuss Python Dictionary sort. Here we will also see the Python create string examples:

  • Python dictionary sort by value
  • Python dictionary sort by key
  • Python dictionary sort by value descending
  • Python dictionary sort by value alphabetically
  • Python dictionary sort by key alphabetically
  • Python dictionary sort reverse
  • Python dictionary sort by key value
  • Python dictionary sort with lambda
  • Python dictionary sort by alphabetically
  • Python dictionary sort by value list
  • Python sort dictionary by value then key