Sort dict on __iter__

I am trying to sort a dict based on its key and return an iterator to the values ​​from the overridden iter method in the class. Is there a more efficient and effective way to do this than creating a new list by inserting into the list when I sort the keys?

+4
source share
4 answers

How about something like this:

def itersorted(d): for key in sorted(d): yield d[key] 
+8
source

To date, the easiest approach and almost certainly the fastest is something like:

 def sorted_dict(d): keys = d.keys() keys.sort() for key in keys: yield d[key] 

You cannot sort without retrieving all keys. Getting all the keys into a list and then sorting that list is the most efficient way to do this; sorting the list is very quick, and selecting a list of keys is as fast as it can be. Then you can either create a new list of values ​​or give values, as shown in the example. Keep in mind that you cannot change the dict if you repeat it (the next iteration will fail), so if you want to change the dict before you finish with the result of sorted_dict (), make it return a list.

+2
source
 def sortedDict(dictobj): return (value for key, value in sorted(dictobj.iteritems())) 

This will create one staging list, the sorted () method returns a real list. But at least this is just one.

+2
source

Assuming you want the default sort order, you can use sorted (list) or list.sort (). If you need your own sorting logic, Python lists support the ability to sort based on the function you are passing in. For example, the following will be a way to sort numbers from smallest to largest (default behavior) using a function.

 def compareTwo(a, b): if a > b: return 1 if a == b: return 0 if a < b: return -1 List.Sort(compareTwo) print a 

This approach is conceptually a little cleaner than manually, creating a new list and adding new values ​​and allowing you to control the sorting logic.

-1
source

Source: https://habr.com/ru/post/1276932/


All Articles