1

As i know dictionary as a data structure in Python is an unordered set of {key: value} pairs

When it is unordered, i expect to get variation of results the following statement:

>>> inner_planets = {1: "Mercury", 2: "Venus", 3: "Earth", 4: "Mars"}
>>> print(inner_planets)
{2: 'Venus', 1: 'Mercury', 3: 'Earth', 4: 'Mars'}
>>> print(inner_planets)
{1: 'Mercury', 4: 'Mars', 2: 'Venus', 3: 'Earth'}
>>> print(inner_planets)
{3: 'Earth', 4: 'Mars', 1: 'Mercury', 2: 'Venus'}
>>> 

instead of this, Python 3.6.3 interactive console prints only one pattern:

>>> inner_planets = {1: "Mercury", 2: "Venus", 3: "Earth", 4: "Mars"}
>>> print(inner_planets)
{1: 'Mercury', 2: 'Venus', 3: 'Earth', 4: 'Mars'}
>>> print(inner_planets)
{1: 'Mercury', 2: 'Venus', 3: 'Earth', 4: 'Mars'}
>>> print(inner_planets)
{1: 'Mercury', 2: 'Venus', 3: 'Earth', 4: 'Mars'}
>>> 

Why?

pobu
  • 402
  • 1
  • 5
  • 13
  • 4
    1) Python 3.6 dicts are ordered. 2) Dictionaries don't randomly change their order just because you print them. You actually have to modify them. – Aran-Fey Jan 25 '18 at 22:16
  • I added [Why is the order in dictionaries and sets arbitrary?](//stackoverflow.com/q/15479928) to the dupe list to show how order is not 'random'. – Martijn Pieters Jan 25 '18 at 22:19
  • Python < 3.6, dictionaries are *unordered*, but iteration order is consistent as long as the dictionary hasn't been modified (keys added or deleted) – juanpa.arrivillaga Jan 25 '18 at 22:19
  • [Here](https://docs.python.org/3/tutorial/datastructures.html) in Python 3.6.4 Docs is explicit written: "It is best to think of a dictionary as an unordered set of key: value pairs" – pobu Jan 25 '18 at 22:22
  • @pobu yes, what is your point? – juanpa.arrivillaga Jan 25 '18 at 22:29

0 Answers0