-3

Is the order of dictionary decided at first print?

I mean that every time when I print the same dictionary, it entries return in the same order. How can I show entries in different orders?

5Ke
  • 1,209
  • 11
  • 28
  • 1
    Does this answer your question? [Are dictionaries ordered in Python 3.6+?](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6) – Ocaso Protal Apr 07 '20 at 07:03

1 Answers1

2

This depends on your python version. In versions older than Python 3.6, dictionaries are not ordered. Printing them may give different results each time. This means you cannot rely on them to return the same order, but neither should you assume that they return keys in a proper random order.

However, in newer versions, python dictionaries are ordered, and the print result will be the same.

In case of ordered dictionaries, the order of a dictionary is not decided when calling print for the first time, but at the moment of creation.

For Python 3.6 or later you can shuffle your dictionary keys and create a new dict:

import random
d = {'a':1, 'b':2, 'c':3, 'd':4}
l = list(d.items())
random.shuffle(l)
d = dict(l)
5Ke
  • 1,209
  • 11
  • 28
  • 1
    "Printing them will give different results each time." No, even in prior versions, printing the dictionary would be *consistent* if *arbitrary*. – juanpa.arrivillaga Apr 07 '20 at 18:51