Home >Backend Development >Python Tutorial >Why Does My Python Dictionary Appear Ordered Despite Being Unordered?

Why Does My Python Dictionary Appear Ordered Despite Being Unordered?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 01:43:11736browse

Why Does My Python Dictionary Appear Ordered Despite Being Unordered?

Dictionary Ordering in Python

Why does a Python dictionary seem to be ordered when it is supposedly unordered?

Consider the following dictionary:

propertyList = {
    "id":           "int",
    "name":         "char(40)",

    "team":         "int",
    "realOwner":    "int",

    "x":            "int",
    "y":            "int",

    "description":  "char(255)",

    "port":         "bool",
    "secret":       "bool",
    "dead":         "bool",
    "nomadic":      "bool",

    "population":   "int",
    "slaves":       "int",
}

When printing the dictionary with "n".join(myDict), an unexpected order is observed:

name
nomadic
dead
port
realOwner
secret
slaves
team
y
x
Population
id
description

While Python dictionaries are indeed unordered, the same order is consistently produced.

Underlying Implementation

In older versions of Python, dictionaries were implemented as hash tables. Hash tables use a function to map keys to specific locations in an array, resulting in an apparently arbitrary but consistent order.

Ordered Dict Implementation

Python has since revised its dict implementation to preserve the order of insertion. This guarantee is effective from Python 3.7 onward. Therefore, the dictionary implementation is no longer purely based on a hash table, although a hash table is still employed in its construction.

The above is the detailed content of Why Does My Python Dictionary Appear Ordered Despite Being Unordered?. 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