Home >Backend Development >Python Tutorial >Are Python 3.6 Dictionaries Ordered, and How Does This Impact Performance?

Are Python 3.6 Dictionaries Ordered, and How Does This Impact Performance?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-21 17:19:101067browse

Are Python 3.6  Dictionaries Ordered, and How Does This Impact Performance?

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.

  • dk_entries array: Stores the dictionary entries in the order they were inserted.
  • dk_indices array: Contains indices that point to the dk_entries array.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn