
I use them commonly when I’m storing credentials locally or in the cloud, working with collections where query times are more important than order, and especially when serializing data. Python’s dictionary structure is an incredible tool for hash-mapping and I use them all the time. For example, tuples are themselves immutable but may contain a structure like a list or an object.

Python dictionaries can use a tuple as a key - but that tuple cannot contain a mutable object. OrderedDict still has some performance benefits in some cases and shouldn’t be discounted entirely in my opinion. Since 3.7 the standard dict object has provided this functionality and has replaced the need for OrderedDict in many cases. Note: Python’s OrderedDict class from the collections module was an often-used alternative to dict objects since it preserved insertion order. Why do you ask? Because Python makes it so easy! In this case, I’ve sorted a dictionary of the alphabet by proximity to the average position. # Create a dictionary with randomly ordered keysĭ = Īs you can see, the combination of the key argument, a Python lambda function, and dictionary comprehension can do a lot of work. TL DR – Use the built-in sorted function with a lambda expression as the key.

For those here from Google for a quick answer, check out the TL DR below: I’ll walk you through some basic gotchas, considerations, and notable options. This involves an intermediary step, or a bold one-liner, but is relatively straightforward.

Fortunately, one can sort a Python dictionary by converting it to a sortable type such as a list.
