Python 字典排序:根据字典长度排序
要根据字典长度排序,可以使用 sorted() 函数和 len() 函数来实现。具体步骤如下:
- 定义一个字典列表。
- 使用
sorted()函数对字典列表进行排序,传入key参数,指定排序的依据为字典的长度,即len()函数。 - 打印排序后的结果。
以下是一个示例代码:
dict_list = [{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5}, {'f': 6, 'g': 7, 'h': 8, 'i': 9}]
sorted_dict_list = sorted(dict_list, key=lambda x: len(x))
for d in sorted_dict_list:
print(d)
运行结果:
{'d': 4, 'e': 5}
{'a': 1, 'b': 2, 'c': 3}
{'f': 6, 'g': 7, 'h': 8, 'i': 9}
根据字典长度排序后,最短的字典是 {'d': 4, 'e': 5},其次是 {'a': 1, 'b': 2, 'c': 3},最长的字典是 {'f': 6, 'g': 7, 'h': 8, 'i': 9}。
原文地址: https://www.cveoy.top/t/topic/qExG 著作权归作者所有。请勿转载和采集!