Từ điển Python: Bài tập-1 với giải pháp
Viết một chương trình Python để sắp xếp [tăng dần và giảm dần] một từ điển theo giá trị.
Giải pháp mẫu-1:
Mã Python:
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print['Original dictionary : ',d]
sorted_d = sorted[d.items[], key=operator.itemgetter[1]]
print['Dictionary in ascending order by value : ',sorted_d]
sorted_d = dict[ sorted[d.items[], key=operator.itemgetter[1],reverse=True]]
print['Dictionary in descending order by value : ',sorted_d]
Đầu ra mẫu:
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}
Trực quan hóa thực thi mã Python:
Công cụ sau đây trực quan hóa những gì máy tính đang làm từng bước khi nó thực hiện chương trình đã nói:
Giải pháp mẫu-2:
Lưu ý: Giá trị từ điển phải cùng loại.
- Sử dụng Dict.Items [] để có được danh sách các cặp Tuple từ D và sắp xếp nó bằng hàm Lambda và Sắp xếp [].
- Sử dụng Dict [] để chuyển đổi danh sách được sắp xếp trở lại từ điển.
- Sử dụng tham số ngược trong Sắp xếp [] để sắp xếp từ điển theo thứ tự ngược lại, dựa trên đối số thứ hai.
Mã Python:
def sort_dict_by_value[d, reverse = False]:
return dict[sorted[d.items[], key = lambda x: x[1], reverse = reverse]]
print["Original dictionary elements:"]
colors = {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4}
print[colors]
print["\nSort [ascending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors]]
print["\nSort [descending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors, True]]
Đầu ra mẫu:
Original dictionary elements: {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4} Sort [ascending] the said dictionary elements by value: {'Red': 1, 'White': 2, 'Green': 3, 'Pink': 4, 'Black': 5} Sort [descending] the said dictionary elements by value: {'Black': 5, 'Pink': 4, 'Green': 3, 'White': 2, 'Red': 1}
Flowchart:
Trực quan hóa thực thi mã Python:
Công cụ sau đây trực quan hóa những gì máy tính đang làm từng bước khi nó thực hiện chương trình đã nói:
Giải pháp mẫu-2:
Lưu ý: Giá trị từ điển phải cùng loại.
Sử dụng Dict.Items [] để có được danh sách các cặp Tuple từ D và sắp xếp nó bằng hàm Lambda và Sắp xếp []. Python Dictionary Exercise Home.
Next: Write a Python program to add a key to a dictionary.
Giới thiệu
Một từ điển trong Python là một tập hợp các mục lưu trữ dữ liệu dưới dạng các cặp giá trị khóa. Trong Python 3.7 và các phiên bản sau này, từ điển được sắp xếp theo thứ tự chèn vật phẩm. Trong các phiên bản trước, họ đã không được đặt hàng.
Trong bài viết này, chúng ta sẽ xem xét làm thế nào chúng ta có thể sắp xếp một từ điển trên cơ sở các giá trị mà chúng chứa.
Sắp xếp từ điển bằng cách sử dụng một vòng lặp
Chúng ta có thể sắp xếp một từ điển với sự trợ giúp của vòng lặp
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}1. Đầu tiên, chúng tôi sử dụng hàm
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}2 để đặt hàng các giá trị của từ điển. Sau đó, chúng tôi lặp qua các giá trị được sắp xếp, tìm các khóa cho từng giá trị. Chúng tôi thêm các cặp giá trị khóa này theo thứ tự được sắp xếp vào một từ điển mới.
Lưu ý: Sắp xếp không cho phép bạn đặt hàng lại từ điển tại chỗ. Chúng tôi đang viết các cặp được đặt hàng trong một từ điển hoàn toàn mới, trống rỗng. Sorting does not allow you to re-order the dictionary in place. We are writing the ordered pairs in a completely new, empty dictionary.
dict1 = {1: 1, 2: 9, 3: 4}
sorted_values = sorted[dict1.values[]] # Sort the values
sorted_dict = {}
for i in sorted_values:
for k in dict1.keys[]:
if dict1[k] == i:
sorted_dict[k] = dict1[k]
print[sorted_dict]
Nếu bạn chạy cái này với trình thông dịch Python, bạn sẽ thấy:
{1: 1, 3: 4, 2: 9}
Bây giờ chúng ta đã thấy cách sắp xếp với các vòng lặp, chúng ta hãy xem xét một giải pháp thay thế phổ biến hơn sử dụng hàm
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}2.
Sắp xếp từ điển bằng cách sử dụng hàm Sắp xếp []
Trước đây chúng tôi đã sử dụng hàm
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}2 để sắp xếp các giá trị của một mảng. Khi sắp xếp từ điển, chúng ta có thể chuyển thêm một đối số cho hàm
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}2 như thế này:
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}6.
Ở đây,
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}7 là một hàm được gọi trên mỗi phần tử trước khi các giá trị được so sánh để sắp xếp. Phương thức
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}8 trên các đối tượng từ điển trả về giá trị của khóa từ điển.
Biểu thức
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}6 sẽ trả về danh sách các khóa có giá trị được sắp xếp theo thứ tự. Từ đó, chúng ta có thể tạo một từ điển mới, được sắp xếp:
dict1 = {1: 1, 2: 9, 3: 4}
sorted_dict = {}
sorted_keys = sorted[dict1, key=dict1.get] # [1, 3, 2]
for w in sorted_keys:
sorted_dict[w] = dict1[w]
print[sorted_dict] # {1: 1, 3: 4, 2: 9}
Sử dụng hàm
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}2 đã giảm lượng mã chúng tôi phải viết khi sử dụng các vòng
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}1. Tuy nhiên, chúng ta có thể kết hợp thêm chức năng
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}2 với hàm
def sort_dict_by_value[d, reverse = False]:
return dict[sorted[d.items[], key = lambda x: x[1], reverse = reverse]]
print["Original dictionary elements:"]
colors = {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4}
print[colors]
print["\nSort [ascending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors]]
print["\nSort [descending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors, True]]
3 cho một giải pháp ngắn gọn hơn để sắp xếp từ điển theo các giá trị.Sắp xếp từ điển bằng mô -đun toán tử và itemgetter []
Mô -đun
def sort_dict_by_value[d, reverse = False]:
return dict[sorted[d.items[], key = lambda x: x[1], reverse = reverse]]
print["Original dictionary elements:"]
colors = {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4}
print[colors]
print["\nSort [ascending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors]]
print["\nSort [descending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors, True]]
4 bao gồm hàm def sort_dict_by_value[d, reverse = False]:
return dict[sorted[d.items[], key = lambda x: x[1], reverse = reverse]]
print["Original dictionary elements:"]
colors = {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4}
print[colors]
print["\nSort [ascending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors]]
print["\nSort [descending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors, True]]
3. Hàm này trả về một đối tượng có thể gọi được trả về một mục từ một đối tượng.Ví dụ: chúng ta hãy sử dụng
def sort_dict_by_value[d, reverse = False]:
return dict[sorted[d.items[], key = lambda x: x[1], reverse = reverse]]
print["Original dictionary elements:"]
colors = {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4}
print[colors]
print["\nSort [ascending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors]]
print["\nSort [descending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors, True]]
3 để tạo một đối tượng có thể gọi được trả về giá trị của bất kỳ từ điển nào với khóa là def sort_dict_by_value[d, reverse = False]:
return dict[sorted[d.items[], key = lambda x: x[1], reverse = reverse]]
print["Original dictionary elements:"]
colors = {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4}
print[colors]
print["\nSort [ascending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors]]
print["\nSort [descending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors, True]]
7:import operator
dict1 = {1: 1, 2: 9}
get_item_with_key_2 = operator.itemgetter[2]
print[get_item_with_key_2[dict1]] # 9
Mỗi từ điển đều có quyền truy cập vào phương pháp
def sort_dict_by_value[d, reverse = False]:
return dict[sorted[d.items[], key = lambda x: x[1], reverse = reverse]]
print["Original dictionary elements:"]
colors = {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4}
print[colors]
print["\nSort [ascending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors]]
print["\nSort [descending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors, True]]
8. Hàm này trả về các cặp giá trị khóa của một từ điển như một danh sách các bộ dữ liệu. Chúng ta có thể sắp xếp danh sách các bộ dữ liệu bằng cách sử dụng hàm def sort_dict_by_value[d, reverse = False]:
return dict[sorted[d.items[], key = lambda x: x[1], reverse = reverse]]
print["Original dictionary elements:"]
colors = {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4}
print[colors]
print["\nSort [ascending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors]]
print["\nSort [descending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors, True]]
3 để kéo giá trị thứ hai của bộ tuple, tức là giá trị của các khóa trong từ điển.Khi nó được sắp xếp, chúng ta có thể tạo một từ điển dựa trên các giá trị đó:
import operator
dict1 = {1: 1, 2: 9, 3: 4}
sorted_tuples = sorted[dict1.items[], key=operator.itemgetter[1]]
print[sorted_tuples] # [[1, 1], [3, 4], [2, 9]]
sorted_dict = {k: v for k, v in sorted_tuples}
print[sorted_dict] # {1: 1, 3: 4, 2: 9}
Với ít nỗ lực hơn, chúng tôi có một từ điển được sắp xếp theo các giá trị!
Vì đối số
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}7 chấp nhận bất kỳ chức năng nào, chúng ta có thể sử dụng các hàm Lambda để trả về các giá trị từ điển để chúng có thể được sắp xếp. Hãy xem làm thế nào.
Sắp xếp từ điển bằng hàm Lambda
Các hàm Lambda là các chức năng ẩn danh, hoặc không tên, trong Python. Chúng ta có thể sử dụng các hàm Lambda để nhận giá trị của một mục từ điển mà không phải nhập mô -đun
def sort_dict_by_value[d, reverse = False]:
return dict[sorted[d.items[], key = lambda x: x[1], reverse = reverse]]
print["Original dictionary elements:"]
colors = {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4}
print[colors]
print["\nSort [ascending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors]]
print["\nSort [descending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors, True]]
4 cho def sort_dict_by_value[d, reverse = False]:
return dict[sorted[d.items[], key = lambda x: x[1], reverse = reverse]]
print["Original dictionary elements:"]
colors = {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4}
print[colors]
print["\nSort [ascending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors]]
print["\nSort [descending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors, True]]
3. Nếu bạn muốn tìm hiểu thêm về Lambdas, bạn có thể đọc về chúng trong hướng dẫn của chúng tôi về các chức năng Lambda trong Python.Kiểm tra hướng dẫn thực hành của chúng tôi, thực tế để học Git, với các thực hành tốt nhất, các tiêu chuẩn được công nghiệp chấp nhận và bao gồm bảng gian lận. Ngừng các lệnh git googling và thực sự tìm hiểu nó!
Chúng ta hãy sắp xếp một từ điển theo các giá trị bằng cách sử dụng hàm Lambda trong đối số
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}7 của
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}2:
dict1 = {1: 1, 2: 9, 3: 4}
sorted_tuples = sorted[dict1.items[], key=lambda item: item[1]]
print[sorted_tuples] # [[1, 1], [3, 4], [2, 9]]
sorted_dict = {k: v for k, v in sorted_tuples}
print[sorted_dict] # {1: 1, 3: 4, 2: 9}
Lưu ý rằng các phương pháp chúng tôi đã thảo luận cho đến nay chỉ hoạt động với Python 3.7 trở lên. Hãy xem những gì chúng ta có thể làm cho các phiên bản trước của Python.
Trả về một từ điển mới với các giá trị được sắp xếp
Sau khi sắp xếp từ điển theo các giá trị, để giữ một từ điển được sắp xếp trong các phiên bản Python trước 3.7, bạn phải sử dụng
Original dictionary elements: {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4} Sort [ascending] the said dictionary elements by value: {'Red': 1, 'White': 2, 'Green': 3, 'Pink': 4, 'Black': 5} Sort [descending] the said dictionary elements by value: {'Black': 5, 'Pink': 4, 'Green': 3, 'White': 2, 'Red': 1}5 - có sẵn trong mô -đun
Original dictionary elements: {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4} Sort [ascending] the said dictionary elements by value: {'Red': 1, 'White': 2, 'Green': 3, 'Pink': 4, 'Black': 5} Sort [descending] the said dictionary elements by value: {'Black': 5, 'Pink': 4, 'Green': 3, 'White': 2, 'Red': 1}6. Những đối tượng này là từ điển giữ thứ tự chèn.
Đây là một ví dụ về việc sắp xếp và sử dụng
Original dictionary elements: {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4} Sort [ascending] the said dictionary elements by value: {'Red': 1, 'White': 2, 'Green': 3, 'Pink': 4, 'Black': 5} Sort [descending] the said dictionary elements by value: {'Black': 5, 'Pink': 4, 'Green': 3, 'White': 2, 'Red': 1}5:
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}0
Sự kết luận
Hướng dẫn này cho thấy làm thế nào một từ điển có thể được sắp xếp dựa trên các giá trị của nó. Đầu tiên chúng tôi sắp xếp một từ điển bằng cách sử dụng hai cho các vòng lặp. Sau đó, chúng tôi đã cải thiện việc sắp xếp của chúng tôi bằng cách sử dụng hàm
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}2. Chúng tôi cũng đã thấy chức năng
def sort_dict_by_value[d, reverse = False]:
return dict[sorted[d.items[], key = lambda x: x[1], reverse = reverse]]
print["Original dictionary elements:"]
colors = {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4}
print[colors]
print["\nSort [ascending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors]]
print["\nSort [descending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors, True]]
3 từ mô -đun def sort_dict_by_value[d, reverse = False]:
return dict[sorted[d.items[], key = lambda x: x[1], reverse = reverse]]
print["Original dictionary elements:"]
colors = {'Red': 1, 'Green': 3, 'Black': 5, 'White': 2, 'Pink': 4}
print[colors]
print["\nSort [ascending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors]]
print["\nSort [descending] the said dictionary elements by value:"]
print[sort_dict_by_value[colors, True]]
4 có thể làm cho giải pháp của chúng tôi cô đọng hơn.Cuối cùng, chúng tôi đã điều chỉnh giải pháp của mình để làm việc trên các phiên bản Python thấp hơn 3,7.
Biến thể của hàm
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Dictionary in ascending order by value : [[0, 0], [2, 1], [1, 2], [4, 3], [3, 4]] Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}2 là phổ biến nhất và đáng tin cậy nhất để sắp xếp từ điển theo các giá trị.