views:

161

answers:

2

I'm porting some code from Python 2 to 3. This is valid code in Python 2 syntax:

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

In Python 3, the dict_items have no method 'sort' - how can I make a workaround for this in Python 3?

+4  A: 

Use items = sorted(dictionary.items()), it works great in both Python 2 and Python 3.

Alex Martelli
Making code that works both in Python 2 and 3 seems like an odd plus to me. It makes more sense to me to make good code in the version you're writing for, which includes meaning `2to3` can translate it if you're writing for Python 2.x.
Mike Graham
@Mike, in the general case, sure, but in this case `sorted` is quite fine (nor will `2to3` "correct it, of course) -- so your suggestion and mine are identical and I don't see the point of your criticism in this comment.
Alex Martelli
In this case it *is* good code in both versions.
gnibbler
@Alex, I have encountered a lot of people who think writing Python 2/Python 3 polyglots is a good thing. I offered my remark (which wasn't intended to criticize your solution) to clarify to anyone reading this that making code that is valid Python 2 and 3 in the same file is a poor goal.
Mike Graham
Yes, that works! Thanks a lot.
DaveWeber
@Dave, glad it helped!
Alex Martelli
+2  A: 

dict.items returns a view instead of a list in Python 3 (somewhat similarly to the iteritems method in Python 2.x). To get a sorted list of the items use

sorted_items = sorted(d.items())

The sorted builtin takes an iterable and returns a new list of its items, sorted.

Mike Graham