Sort dictionary by value Python
In this post, you will learn how to sort a dictionary by value in Python programming.
Python has an in-built dictionary called dict, which we can use to create an arbitrary definition of the character string. The dict() is a constructor which is used to create instances of the class dict. Dictionary is a collection whose values are accessible by key. The dictionary is a mapping of key & value.
Sort a Dictionary by Value using sorted()
Python provides a predefined function sorted() that returns a sorted list of the specified list. It accepts both object types number and string. Numbers are sorted numerically and strings are sorted alphabetically. But, we cannot provide a list containing both.
sorted(iterable, key, reverse)
Here, the iterable is the required parameter that contains either sort, list, dictionary, tuple. The key is the optional parameter which is a function to decide the order parameter, the reverse is also optional which accepts a boolean value. False will sort ascending, True will sort descending.
Using lambda as key
At the start of our code, we define a dictionary called 'veg_dict' that stores the names of vegetables as keys and the quantity as values. Then, we use the sorted() method to sort the orders dictionary by value. We have used lambda function as key to sort by value. A lambda function is a small anonymous function which takes any number of arguments but can only have one expression.
veg_dict = {"Potato":20, "Onion": 4, "Garlic": 1, "Tomata": 2, "Chilli":4}
veg_dict = sorted(veg_dict.items(), key=lambda x:x[1])
sortdict = dict(veg_dict)
print(sortdict)
Output of the above code:
{'Garlic': 1, 'Tomata': 2, 'Onion': 4, 'Chilli': 4, 'Potato': 20}
Using itemgetter as key
Here, we have used the itemgetter() method of the operator module as a key to sort the dictionary by value. The itemgetter() function returns a callable object from its operand.
import operator
marks_dict = {"Somya":55, "Tristha": 62, "Priska": 97, "Abhi": 71}
marklist= sorted(marks_dict.items(), key=operator.itemgetter(1))
sortdict=dict(marklist)
print(sortdict)
Output of the above code:
{'Somya': 55, 'Tristha': 62, 'Abhi': 71, 'Priska': 97}
Using dict.items() with sorted
items_dict = {"Pen":20, "Pencil": 10, "Notebook": 5, "Shapner": 2, "Eraser":3}
items_list=sorted((value, key)
for (key,value) in items_dict.items())
sortdict=dict([(k,v)
for v,k in items_list])
print(sortdict)
Output of the above code:
{'Shapner': 2, 'Eraser': 3, 'Notebook': 5, 'Pencil': 10, 'Pen': 20}
Related Articles
Add key value pair to dictionary PythonCount vowels in a string Python
Pascal triangle pattern in Python
Python program to map two lists into a dictionary
Python convert dict to xml
Python dict inside list
Convert dictionary to dataframe Python
Python convert xml to dict
Trigonometric functions Python Numpy
Python Pandas Dataframe to CSV
Python Pandas DataFrame
Convert list to dictionary Python
Python dict inside list
Convert dictionary to dataframe Python
Python Pandas CSV to Dataframe
Convert List to Dataframe Python
Python add list to list
Difference between tuple and list in Python
Convert Excel to CSV Python Pandas
Alphabetical order Python
Python | Generate QR Code using pyqrcode module