Home  >  Article  >  Backend Development  >  Understanding the order of Python dictionaries

Understanding the order of Python dictionaries

WBOY
WBOYforward
2024-02-09 20:42:04550browse

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.")

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.

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.

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete