Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the ordering of a python dictionary

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

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 (the order of the dictionary):

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.
like image 850
Mech Avatar asked Jan 29 '26 10:01

Mech


2 Answers

This depends upon the version of Python you are using.

Before Python 3.6

Dictionaries used the ordering of the underlying hash function. Several types have salted hashes, so this means you obtain different order on each invocation.

Python 3.6+

Dictionaries are insertion ordered, i.e., dictionaries remember the order of items inserted. From the docs:

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon

Python 3.7

Guido van Rossum announced on that as of Python 3.7 dicts in all Python implementations must preserve insertion order.

like image 164
lmiguelvargasf Avatar answered Feb 01 '26 00:02

lmiguelvargasf


Unlike in a list, items stored in a dictionary aren't kept in any particular order; in fact, Python randomizes their left-to-right order to provide quick lookup. Keys provide the symbolic locations (not physical) of items in a dictionary. If you think in a list as ordered collections of objects, you can think of dictionaries as unordered collections. The items are stored and fetched by key, instead of by positional offset :)

like image 20
Franger Rodofo Cuevas Beltrán Avatar answered Jan 31 '26 22:01

Franger Rodofo Cuevas Beltrán



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!