Python 2 中的 dict_items.sort() 在 Python 3 中的用法

1 投票
2 回答
6001 浏览
提问于 2025-04-15 20:26

我正在把一些代码从Python 2转到Python 3。在Python 2的语法中,这段代码是有效的:

def print_sorted_dictionary(dictionary):  
    items=dictionary.items()  
    items.sort()

但是在Python 3中,字典的项(dict_items)没有'sort'这个方法——我该怎么在Python 3中解决这个问题呢?

2 个回答

3

dict.items 在 Python 3 中返回的是一个视图,而不是一个列表(这和 Python 2.x 中的 iteritems 方法有点像)。如果你想要得到一个排序后的列表,可以使用

sorted_items = sorted(d.items())

内置的 sorted 函数可以接收一个可迭代的对象,并返回一个新的、排序好的列表。

10

可以用 items = sorted(dictionary.items()) 这个方法,它在 Python 2 和 Python 3 中都很好用。

撰写回答