编写一个程序将字典转换为列表,列表的每一个元素表示一个键值对,并按键排序。
- 定义函数
dict_to_sorted_list()
,其参数为dictionary
。 - 在函数中,将字典转换为列表,其中每个列表的元素包含键及其相应的值。
- 按升序对此列表排序。
- 返回排序后的列表。
示例输入
{"car": 3, "bus": 2, "train": 5}
示例输出
[['bus', 2], ['car', 3], ['train', 5]]
本题涉及列表推导式的进阶使用,还涉及了排序函数sorted()。
def dict_to_sorted_list(dictionary):
# 此处编写你的代码
return sorted([[key,value] for (key,value) in dictionary.items()])
# 获取输入转为字典
dictionary = eval(input())
# 调用函数
print(dict_to_sorted_list(dictionary))