Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a dict on __iter__

I am trying to sort a dict based on its key and return an iterator to the values from within an overridden iter method in a class. Is there a nicer and more efficient way of doing this than creating a new list, inserting into the list as I sort through the keys?

like image 274
Dan Avatar asked Sep 19 '08 14:09

Dan


People also ask

How do you sort a dictionary for a loop in Python?

Sort Dictionary Using a for Loop We can sort a dictionary with the help of a for loop. First, we use the sorted() function to order the values of the dictionary. We then loop through the sorted values, finding the keys for each value. We add these key-value pairs in the sorted order into a new dictionary.

Can you sort a dictionary Python by key?

To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse . Dictionaries are unordered data structures.


1 Answers

How about something like this:

def itersorted(d):
    for key in sorted(d):
        yield d[key]
like image 109
dF. Avatar answered Sep 27 '22 20:09

dF.