首頁 > 後端開發 > Python教學 > 理解Python字典的順序

理解Python字典的順序

WBOY
發布: 2024-02-09 20:42:04
轉載
587 人瀏覽過

理解Python字典的順序

問題內容

有人可以解釋 python (v3.5) 字典是如何排序的嗎?

data = {"john": 23, "rick": 33, "mary": 63, "ron": 23, "joel": 51}

for key in data:
        print("your name is " + key + ", and you are also " + str(data[key]) + " years old.")
登入後複製

實際輸出:

your name is rick, and you are also 33 years old.
your name is ron, and you are also 23 years old.
your name is mary, and you are also 63 years old.
your name is john, and you are also 23 years old.
your name is joel, and you are also 51 years old.
登入後複製

預期輸出(字典的順序):

Your name is John, and you are also 23 years old.
Your name is Rick, and you are also 33 years old.
Your name is Mary, and you are also 63 years old.
Your name is Ron, and you are also 23 years old.
Your name is Joel, and you are also 51 years old.
登入後複製

正確答案


這取決於您使用的 Python 版本。

Python 3.6 之前

字典使用底層雜湊函數的排序。多種類型具有加鹽哈希,因此這意味著您在每次調用時獲得不同的順序。

Python 3.6

字典是按插入順序排列的,即字典會記住插入項目的順序。來自文檔

Python 3.7

Guido van Rossum 在 中宣布從 Python 3.7 開始所有 Python 實作都必須保留插入順序

以上是理解Python字典的順序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板