How do you sort a dictionary in Python?

When sorting by value, is there a cleaner way than sorted(d.items(), key=lambda x: x[1])? I keep having to look it up every time.

by 주말개발자683

8 answers

Just use operator.itemgetter(1). If you don't want to add an extra import line, lambda is the answer.

by 궁금한사람456 · ▲0

True, I look it up every time too lol

by 무한도전러666 · ▲0

sorted(d.items(), key=operator.itemgetter(1)) is the cleanest. It's also marginally faster than lambda, and just from the name you can immediately tell what it's pulling out, which is nice.

by 취준생김씨505 · ▲0

Isn't that just something you memorize? It's one line—I don't see why you'd bother hunting for a cleaner version. The searching habit itself isn't bad, but this is at a level where it's not even worth searching for.

by 디지털노마드599 · ▲0

I use value-based sorting really often in practice, and just memorizing sorted(d.items(), key=lambda x: x[1], reverse=True) covers most cases. A lot of people use -x[1] for descending order, but if the values are strings, you can't prepend a minus sign, so it immediately throws an error. reverse=True is safer.

by AI덕후120 · ▲0

These days, I just use Counter or pandas. Once the data volume gets large, even running sorted once feels like a burden. That said, it probably depends on the case.

by 주말개발자96 · ▲0

This is right lol. But since dicts preserve insertion order as of Python 3.7, think again about whether you really need sorting. If it's just for output, you can often just output them in insertion order.

by 지나가던행인257 · ▲0

Any source? I benchmarked before that itemgetter is faster than lambda, but in my environment the difference was almost noise level. I get using it for readability, but mentioning performance seems a bit much.

by 밤샘코더991 · ▲0