Dictionary Python có cặp khóa-giá trị. Trong một số tình huống, chúng ta cần các mục của dictionary được sắp xếp theo khóa. Trong bài viết này, chúng ta sẽ thấy các cách khác nhau để lấy output đã sắp xếp từ các mục trong dictionary.
Sử dụng Module Operator
Module Operator có hàm itemgetter có thể lấy 0 làm chỉ số tham số đầu vào cho các khóa của dictionary. Chúng ta áp dụng hàm sorted lên trên itemgetter và lấy output đã sắp xếp.
Ví dụ
dict = {12: 'Mon', 21: 'Tue', 17: 'Wed'}
import operator
print("\nDictionary cho trước", str(dict))
print("Thứ tự sắp xếp từ dictionary cho trước")
for k, n in sorted(dict.items(), key=operator.itemgetter(0), reverse=False):
print(k, " ", n)
Kết quả
Chạy đoạn code trên cho kết quả sau:
Dictionary cho trước {12: 'Mon', 21: 'Tue', 17: 'Wed'}
Thứ tự sắp xếp từ dictionary cho trước
12 Mon
17 Wed
21 Tue
Sử dụng phương thức Sorted
Phương thức sorted có thể áp dụng trực tiếp lên dictionary để sắp xếp các khóa.
Ví dụ
dict = {12: 'Mon', 21: 'Tue', 17: 'Wed'}
# Sử dụng sorted()
print("Dictionary cho trước", str(dict))
print("Thứ tự sắp xếp từ dictionary cho trước")
for k in sorted(dict):
print(dict[k])
Kết quả
Chạy đoạn code trên cho kết quả sau:
Dictionary cho trước {12: 'Mon', 21: 'Tue', 17: 'Wed'}
Thứ tự sắp xếp từ dictionary cho trước
Mon
Wed
Tue
Sử dụng dict.items()
Chúng ta cũng có thể áp dụng sorted cho dict.items. Trong trường hợp này, cả khóa và giá trị đều có thể in ra.
Ví dụ
dict = {12: 'Mon', 21: 'Tue', 17: 'Wed'}
# Sử dụng d.items()
print("\nDictionary cho trước", str(dict))
print("Thứ tự sắp xếp từ dictionary cho trước")
for k, i in sorted(dict.items()):
print(k, i)
Kết quả
Chạy đoạn code trên cho kết quả sau:
Dictionary cho trước {12: 'Mon', 21: 'Tue', 17: 'Wed'}
Thứ tự sắp xếp từ dictionary cho trước
12 Mon
17 Wed
21 Tue