Are Python 3.6 Dictionaries Ordered?
In Python versions 3.6 and above, dictionaries maintain an insertion order for their elements. This behavior is known as "insertion ordering." Unlike OrderedDict, which offers advanced order-related capabilities, dictionaries only retain the order of element insertions.
How Python 3.6 Enhances Dictionary Performance While Preserving Order
The Python 3.6 dictionary implementation employs a dual-array approach to address memory efficiency while maintaining insertion order.
This approach avoids the need for a sparsely populated array, which was the case in previous implementations. Instead, it only stores necessary entries and their indices, resulting in more compact memory usage.
Visual Representation:
Consider the following dictionary:
d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'}
Under the new implementation, it would be stored as:
indices = [None, 1, None, None, None, 0, None, 2] entries = [[-9092791511155847987, 'timmy', 'red'], [-8522787127447073495, 'barry', 'green'], [-6480567542315338377, 'guido', 'blue']]
Compared to the previous implementation, this approach significantly reduces memory wastage.
Benefits of the New Dictionary Implementation
Primarily, the new implementation improves memory usage while preserving insertion order. While speed differences between the old and new implementations aren't dramatic, certain operations like iteration and resizing may see performance boosts.
The above is the detailed content of Are Python 3.6 Dictionaries Ordered, and How Does This Impact Performance?. For more information, please follow other related articles on the PHP Chinese website!