Python Forum
mydict.items() is not a list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: mydict.items() is not a list (/thread-26611.html)



mydict.items() is not a list - Skaperen - May-07-2020

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?


RE: mydict.items() is not a list - perfringo - May-07-2020

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'}



RE: mydict.items() is not a list - DeaD_EyE - May-07-2020

Here is an example with itemgetter: https://python-forum.io/Thread-Sort-last?pid=113226#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.