How to sort a 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}]

Updated on: 17-Jun-2020

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements