JHD
JHD

Reputation: 65

Maintaining a sorted view of dict values?

I have a dict containing about 50,000 integer values, and a set that contains the keys of 100 of them. My inner loop increments or decrements the values of the dict items in an unpredictable way.

Periodically I need to replace one member of the set with the key of the largest element not already in the set. As an aside, if the dict items were sorted, the order of the sort would change slightly, not dramatically, between invocations of this routine.

Re-sorting the entire dict every time seems wasteful, although maybe less so given that it's already "almost" sorted. While I may be guilty of premature optimization, performance will matter as this will run a very large number of iterations, so I thought it worth asking my betters whether there's an obviously more efficient and pythonic approach.

I'm aware of the notion of dict "views" - Windows onto the contents which are updated as the contents change. Is there such a thing as a "sorted view"?

Upvotes: 0

Views: 75

Answers (1)

Francesco
Francesco

Reputation: 4250

Instead of using a dict you could use a Counter object which has a neat most_common(n) method which

Return a list of the n most common elements and their counts from the most common to the least.

Upvotes: 0

Related Questions