Python Forum

Full Version: mydict.items() is not a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
what i get from mydict.items() is not a list. i can't .sort() it. it have to make a list from it to be able to sort it in-place, defeating the performance advantage of sorting in place. what can be done to have the list of items in sorted order with that kind of performance?
One can sort dictionaries with sorted(), not in-place though:

>>> d = {5: 'five', 3: 'three', 2: 'two'}
>>> sorted(d)
[2, 3, 5]
>>> sorted(d.items())
[(2, 'two'), (3, 'three'), (5, 'five')]
>>> dict(sorted(d.items()))
{2: 'two', 3: 'three', 5: 'five'}
Here is an example with itemgetter: https://python-forum.io/Thread-Sort-last...#pid113226
This is useful, if you have a list with dicts and the dicts do have all the same keys.
Sorting them with the key function together with itemgetter is very handy.