Understanding the order of Python dictionaries

WBOY
Release: 2024-02-09 20:42:04
forward
547 people have browsed it

Understanding the order of Python dictionaries

Question content

Can someone explain how python (v3.5) dictionaries are sorted?

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.")
Copy after login

Actual output:

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.
Copy after login

Expected output (lexicographic order):

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.
Copy after login

Correct answer


This depends on the version of Python you are using.

Before Python 3.6

Dictionaries are sorted using the underlying hash function. Several types have salted hashes, so this means you get a different order on each call.

Python 3.6

The dictionary is arranged in insertion order, that is, the dictionary remembers the order in which items are inserted. From Documentation:

Python 3.7

Guido van Rossum announced in that starting with Python 3.7 all Python implementations must preserve insertion order .

The above is the detailed content of Understanding the order of Python dictionaries. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!