#!/usr/bin/python
# Write Python 3 code in this online editor and run it.
# 根据键排序
dict1 = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
sorted_dict1 = sorted(dict1)
print(sorted_dict1) # 输出: ['apple', 'banana', 'orange', 'pear']
# 根据键排序
dict1 = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
sorted_dict1 = sorted(dict1.items())
print(sorted_dict1) # 输出: [('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]
# 根据键排序
dict1 = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
sorted_dict1 = dict(sorted(dict1.items()))
print(sorted_dict1) # 输出: ('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)
# 根据值排序
dict2 = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
sorted_dict2 = dict(sorted(dict2.items(), key=lambda item: item[1]))
print(sorted_dict2) # 输出: [('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)]
# 根据值排序
data = [{"probabily":"98%","Iscore":"99","Oscore":"97","weChat":"小樱","Ouid":"3"},
{"probabily":"93%","Iscore":"90","Oscore":"90","weChat":"雏田","Ouid":"4"}
]
sorted_dict2 = sorted(data, key=lambda item: item["probabily"])
print(sorted_dict2) # 输出: [{'probabily': '93%', 'Iscore': '90', 'Oscore': '90', 'weChat': '雏田', 'Ouid': '4'}, {'probabily': '98%', 'Iscore': '99', 'Oscore': '97', 'weChat': '小樱', 'Ouid': '3'}]
sorted_dict2 = sorted(data, key=lambda item: item["probabily"],reverse=True)
print(sorted_dict2) # 输出: [{'probabily': '98%', 'Iscore': '99', 'Oscore': '97', 'weChat': '小樱', 'Ouid': '3'}, {'probabily': '93%', 'Iscore': '90', 'Oscore': '90', 'weChat': '雏田', 'Ouid': '4'}]
python 之字典排序
最新推荐文章于 2024-06-18 00:22:55 发布