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.
This depends upon the version of Python you are using.
Dictionaries used the ordering of the underlying hash function. Several types have salted hashes, so this means you obtain different order on each invocation.
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
Guido van Rossum announced on that as of Python 3.7 dicts in all Python implementations must preserve insertion order.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With