Sort dictionary in Python

Posted on

Python dictionary stores data in key-value pairs. In some situations, programmers need to sort the dictionary object as per their requirement which may be based on key or value. To sort dictionary object, you can user sorted() method and pass either keys or values from the dictionary which sorts the elements in their natural order. For example, if the elements are all integers, then smaller numbers go earlier in the list. If the elements are all strings, they are arranged in alphabetic order. Below examples demonstrate different ways to sort the dictionary based on key or value.

1) Sort dictionary based on keys

Output

2) Sort dictionary based on keys in descending order

Output

3) Sort dictionary based on values

Output

4) Sort dictionary based on values in descending order

Output

 

Stay tuned for more updates and tutorials !!!

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.