Are dictionaries ordered in Python 3.6+?
Take a look:
But hold your horses! In Python 3.6, while dictionaries do have a good memory of the order, it's more of a personal hobby and not necessarily promised behavior.
What's Inside the Box?
In Python 3.7+, dictionaries have developed a sense of order (finally!). This change is like taking a wild horse (okay, a really lazy horse) and giving it steadfast discipline.
Two Arrays to tango
How is this order achieved, you ask? Simple, Python employs two arrays under the hood.
- The first array is responsible for keeping the party guests (keys and values).
- The second array maintains an index for each guest, tracking their order of arrival.
Doing more with less
The whole shebang results in a nice little reduction in memory usage. In fact, memory overhead is down 20-25% compared to Python 3.5 or earlier. Python 3.8 even added a cherry on top with reverse iterable dictionaries. Talk about dressing for the occasion!
Dicts in tuxedos (OrderedDict)
Now, there is less need to invite collections.OrderedDict
to the party because regular dicts can cut some rug themselves. However, OrderedDict
still has a few surprise moves, like popitem(last=True)
. Plus, it checks the entire dance routine (OrderedDicts
check order of items for equality, while standard dicts just compare moves).
Python 3.6: The Unpromised Dance
Recursive? I prefer the term "classic". Remember that while the 3.6 party has a dance order, keep the PY-D (Public Python Disclaimer) in mind: we're dealing with a personal preference, not guaranteed order. It's now legit with Python 3.7.
Get the Party Started
Now let's take this theory for a spin on the API interface or JSON format dance floor. Now, you can just rely on standard dictionaries without thinking twice. If you are low-key and like vintage, keep using OrderedDict
. Old is gold, right?
The Evolution Macarena
Old dance moves, meet the new groove: ordered dictionaries in Python transition. You can now ditch the excess and embrace the less-is-more mantra with linked-list or simple caching mechanism.
Was this article helpful?