
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Sort Python Dictionary by Datatype
You can sort a list of dictionaries by values of the dictionary using the sorted function and passing it a lambda that tells which key to use for sorting. For example,
A = [{'name':'john','age':45}, {'name':'andi','age':23}, {'name':'john','age':22}, {'name':'paul','age':35}, {'name':'john','age':21}] new_A = sorted(A, key=lambda x: x['age']) print(new_A)
This will give the output:
[{'name': 'john', 'age': 21}, {'name': 'john', 'age': 22}, {'name': 'andi', 'age': 23}, {'name': 'paul', 'age': 35}, {'name': 'john', 'age': 45}]
You can also sort it in place using the sort function instead of the sorted function. For example,
A = [{'name':'john','age':45}, {'name':'andi','age':23}, {'name':'john','age':22}, {'name':'paul','age':35}, {'name':'john','age':21}] A.sort(key=lambda x: x['age']) print(A)
This will give the output:
[{'name': 'john', 'age': 21}, {'name': 'john', 'age': 22}, {'name': 'andi', 'age': 23}, {'name': 'paul', 'age': 35}, {'name': 'john', 'age': 45}]
Advertisements