2 ways to sort a dictionary in python by values or keys

Spread the love

In this tutorial, You will learn how to sort a dictionary in python by values or keys.

#method 1 : in this method, we will sort the dictionary by using values and keys using simple method sorted.

data = {1:'ravi', 22:'david',3:'ramu', 44:'steve'} sorted_values=sorted(data.values()) print(sorted_values) sorted_keys=sorted(data.keys()) print(sorted_keys)

Output:

['david', 'ramu', 'ravi', 'steve']
[1, 3, 22, 44]

Note: It is not possible to sort a dictionary, Dictionaries are inherently orderless,  You will get a output with tuple with lists in this 2nd method.

# method 2 : in this method, we will import operator module to execute this program.

# method 2 import operator #sort by values sorted_values = sorted(data.items(), key=operator.itemgetter(1)) print(sorted_values) #sort by keys sorted_keys = sorted(data.items(), key=operator.itemgetter(0)) print(sorted_keys)

Output:

[(22, 'david'), (3, 'ramu'), (1, 'ravi'), (44, 'steve')]
[(1, 'ravi'), (3, 'ramu'), (22, 'david'), (44, 'steve')]

 

admin

admin

Leave a Reply

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