按键对字典进行排序

Beginner

This tutorial is from open-source community. Access the source code

简介

字典是 Python 中一种重要的数据结构。它们用于以键值对的形式存储数据。然而,有时需要按键对字典进行排序。在这个挑战中,你将负责编写一个按键对字典进行排序的函数。

按键对字典进行排序

编写一个函数 sort_dict_by_key(d, reverse=False),该函数接受一个字典 d,并返回一个按键排序的新字典。该函数应有一个默认值为 False 的可选参数 reverse。如果 reverseTrue,则字典应按逆序排序。

def sort_dict_by_key(d, reverse = False):
  return dict(sorted(d.items(), reverse = reverse))
d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}
sort_dict_by_key(d) ## {'five': 5, 'four': 4, 'one': 1, 'three': 3, 'two': 2}
sort_dict_by_key(d, True)
## {'two': 2, 'three': 3, 'one': 1, 'four': 4, 'five': 5}

总结

在这个挑战中,你需要编写一个按键对字典进行排序的函数。你学习了如何使用 sorted() 函数对字典中的元组对列表进行排序,并使用 dict() 函数将其转换回字典。你还学习了如何在 sorted() 中使用 reverse 参数对字典进行逆序排序。