
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Ways to sort list of dictionaries by values in Python
Here one dictionary is given, our task is to sort by their values. Two values are present in this dictionary one is name and another is roll. First we display sorted list by their roll using lambda function and in-built sorted function.
Second we display sorted list by the name and roll and third by their name.
Example code
# Initializing list of dictionaries my_list1 = [{ "name" : "Adwaita", "roll" : 100}, { "name" : "Aadrika", "roll" : 234 }, { "name" : "Sakya" , "roll" : 23 }] print ("The list is sorted by roll: ") print (sorted(my_list1, key = lambda i: i['roll']) ) print ("\r") print ("The list is sorted by name and roll: ") print (sorted(my_list1, key = lambda i: (i['roll'], i['name'])) ) print ("\r") print ("The list is sorted by roll in descending order: ") print (sorted(my_list1, key = lambda i: i['roll'],reverse=True) )
Output
The list is sorted by roll: [{'name': 'Sakya', 'roll': 23}, {'name': 'Adwaita', 'roll': 100}, {'name': 'Aadrika', 'roll': 234}] The list is sorted by name and roll: [{'name': 'Sakya', 'roll': 23}, {'name': 'Adwaita', 'roll': 100}, {'name': 'Aadrika', 'roll': 234}] The list is sorted by roll in descending order: [{'name': 'Aadrika', 'roll': 234}, {'name': 'Adwaita', 'roll': 100}, {'name': 'Sakya', 'roll': 23}]
- Related Questions & Answers
- Ways to sort list of dictionaries by values in Python Using itemgetter
- Ways to sort list of dictionaries using values in python
- Ways to sort list of dictionaries by values in Python Using lambda function
- Sort list of dictionaries by values in C#
- How to sort a list of dictionaries by values of dictionaries in C#?
- Python program to Sort a List of Dictionaries by the Sum of their Values
- How do I sort a list of dictionaries by values of the dictionary in Python?
- Python – Sort Dictionaries by Size
- Python - Filter dictionaries by values in Kth Key in list
- Sort Python Dictionaries by Key or Value
- Flatten given list of dictionaries in Python
- Python | Sort the values of first list using second list
- Sort list of tuples by specific ordering in Python
- How to sort a dictionary in Python by values?
- Program to count number of ways we can make a list of values by splitting numeric string in Python
Advertisements