Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge
  • All
  • C#
  • MVC
  • Web API
  • Azure
  • IIS
  • JavaScript
  • Angular
  • Node.js
  • Java
  • Python
  • SQL Server
  • SEO
  • Entrepreneur
  • Productivity

Sort a Dictionary by Value in Python

In Python, the dictionary class doesn't have any provision to sort items in its object. Hence, some other data structure, such as the list has to be used to be able to perform sorting.

To begin with, our test data is following dictionary object having names and marks of students.

The dict class has items() method that returns a view of list of tuples, each tuple having key and value of each pair in a dictionary.

Example: Create List of Dictionary Values
markdict={"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist=list(markdict.items())
print(marklist)
Output
[('Tom', 67), ('Tina', 54), ('Akbar', 87), ('Kane', 43), ('Divya', 73)]

The list allows its items to be rearranged in place. We can employ a simple bubble sort to arrange tuples according to the mark component, as shown below.

Example: Bubble Sorting of List
markdict={"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
l=len(marklist)
for i in range(l-1):
    for j in range(i+1,l):
<pre className="language-python"><code>markdict={"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
l=len(marklist)
for i in range(l-1):
    for j in range(i+1,l):
        if marklist[i][1]&gt;marklist[j][1]:
            t=marklist[i]
            marklist[i]=marklist[j]
            marklist[j]=t
    sortdict=dict(marklist)
    print(sortdict)
Output
{'Kane': 43, 'Tina': 54, 'Tom': 67, 'Divya': 73, 'Akbar': 87}

Using sorted() Method

Understandably, this solution is slow and inefficient. Python's built-in function library has a better solution for this in the form of the sorted() function.

Example: sorted()
markdict = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
<pre className="language-python"><code>markdict = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist = sorted(markdict.items(), key=lambda x:x[1])
sortdict = dict(marklist)
print(sortdict)
Output
{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

Another option is to use the itemgetter() function as defined in the operator module bundled with Python's standard library. The itemgetter() function returns a callable object from its operand.

Example: Sort Dict using itemgetter()
import operator

<pre className="language-python"><code>import operator

markdict = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist= sorted(markdict.items(), key=operator.itemgetter(1)) 
sortdict=dict(marklist)
print(sortdict)
Output
{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

Finally, we shall use the dict.items() method along with the sorted() function to first obtain (marks, name) tuples and then reconstruct dictionary in a sorted order of marks.

Example: sorted()
markdict = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist=sorted((value, key) for (key,value) in markdict.items())
sortdict=dict([(k,v) for v,k in marklist])
print(sortdict)
Output
{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.