Python 3中的Python 2 dict_items.sort()

Dav*_*ber 1 python python-3.x

我正在将一些代码从Python 2移植到3.这是Python 2语法中的有效代码:

def print_sorted_dictionary(dictionary):  
    items=dictionary.items()  
    items.sort()
Run Code Online (Sandbox Code Playgroud)

在Python 3中,dict_items没有方法'sort' - 我如何在Python 3中为此做出解决方法?

Ale*_*lli 8

使用items = sorted(dictionary.items()),它在Python 2 和 Python 3 中都很有用.

  • @Alex,我遇到过很多人认为编写Python 2/Python 3 polyglots是一件好事.我提出了我的意见(这并不是为了批评你的解决方案)向任何读到这一点的人澄清,在同一个文件中制作有效的Python 2和3的代码是一个糟糕的目标. (2认同)