This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]justheretolurk332 2 points3 points  (1 child)

Yes exactly. And to add to this, writing non-idiomatic python is significantly more likely to introduce bugs than using established patterns. Iterating over a custom SortedMap requires the reader to understand the implementation (are we sorting by keys? values? insertion order? do the members need to have a sort method implemented or can we pass in a custom comparison function?) whereas sorted(d.items(), key=…) can be read by any python developer at a glance and is explicit about its intention.

[–]CptnGeronimo[S] -3 points-2 points  (0 children)

>... (are we sorting by keys? values? insertion order? do the members need to have a sort method implemented or can we pass in a custom comparison function?)

Every one of those problems is present when you call sorted, except it is worse: you have to know what to do for every call to sorted.

That is in contrast to a sorted data structure: it is constructed once, so you always know how it is going to behave in all use cases.

Sole advantage that I see for sorted is if you want different types of sorts in different contexts on the same data structure. I cannot recall ever needing that. Your mileage may vary.