Are dictionaries ordered in Python 3.6+?
Are dictionaries ordered in Python 3.6+? 📚
If you've ever worked with dictionaries in Python, you might have wondered if they maintain the order in which the key-value pairs are inserted. Well, the answer to that question is, yes, starting from Python 3.6!
The New Dictionary Implementation 🚀
In Python 3.6, a new implementation for dictionaries was introduced, using a "compact" representation pioneered by PyPy. This new implementation brings significant improvements in terms of memory usage, with the new dict()
being between 20% and 25% smaller compared to Python 3.5.
The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon. In other words, while dictionaries are currently ordered in Python 3.6+, there's no guarantee that this will always be the case in future versions of the language.
This design decision was made to maintain backward compatibility with older versions of Python, where dictionaries had random iteration order. By allowing time for the new dict()
implementation to be used in several releases, potential issues can be identified and addressed before making ordering a mandatory language feature.
The Future of Ordered Dictionaries 💡
If you're hoping for a firm guarantee of ordered dictionaries, I have exciting news for you! Starting from Python 3.7, ordered dictionaries are officially guaranteed. This means you can rely on the insertion order being preserved in future versions of Python.
Summary 📝
To summarize, dictionaries in Python 3.6+ are ordered, but this behavior is currently considered an implementation detail and may change in future versions. However, from Python 3.7 onwards, ordered dictionaries are guaranteed.
Now that you know the ins and outs of dictionary ordering in Python, you can confidently write code that relies on this behavior when working with key-value pairs.
So go ahead, embrace the power of ordered dictionaries and build amazing Python applications! 😎💻
Did you find this article helpful? Share your thoughts in the comments below and let's discuss the fascinating world of Python dictionaries! 🔥🐍
<hr />
Update December 2017: Dictionaries retaining insertion order is guaranteed for Python 3.7