Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Sắp xếp Python Dictionary theo datatype

Sắp xếp list of dicts theo value của key cụ thể dùng sorted() + lambda.

Ví dụ

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)

Kết quả: sắp xếp theo age tăng dần.

Dùng list.sort(key=...) để sort in-place.