-2

I hope the code explains my question better:

 dic={'one':'root', 'two':'leaf', 'three':'tree', 'four':'fruit'}
 for n in dic.keys():
     n = dic.get(n)
     print(n)

Output:

fruit
leaf
root
tree

Can anyone explain please, what is the logic behind this kind of sequence in output? I know, Dict does not support indexing. Then how does it work? why 'fruit' is at first and 'leaf' second?

1 Answers1

2

Dictionaries are ordered according to how the keys were inserted starting in Python 3.6: Are dictionaries ordered in Python 3.6+?

Prior to Python 3.6, the ordering of keys in dictionaries was not specified, and cannot be relied upon.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • I declared new dict variable with same keys and values. The same thing happening. –  Jun 28 '20 at 08:08
  • 1
    @RafiSarker why did you expect a different thing to happen? – jonrsharpe Jun 28 '20 at 08:10
  • May be I did not get well about the 'how the keys were inserted'. assigning all values at once. @jonrsharpe –  Jun 28 '20 at 08:22
  • @RafiSarker: In Python 3.6 and later, when you create a dict using the syntax like `{'a': 1, 'b': 2}` with the values in it from the beginning, that ordering is preserved. Prior to 3.6, the ordering is not preserved. – John Zwinck Jun 28 '20 at 08:36