How to sort a Python dictionary by datatype?

PythonProgramming

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}]
raja
Published on 18-Apr-2018 15:29:03
Advertisements