0
dict1={'s':1,'a':2}
dict1.keys()

once time {'a','s'} and other time {'s','a'} Why ?

   set1={'a','b'}
    set2={'b','c'}
    print(set1 | set2)

once time {'a','b','c'}, second time: {'c','b','a'} and etc. Why ? How can I print in deterministic order ?

  • 3
    `dict`s and `set`s are _**un-ordered**_ data structures. They have a random order when created, and it changes as the dictionary is operated upon. – Christian Dean Sep 08 '17 at 17:45
  • 'No order' is more accurate than 'random order'. You can sort the keys by some criteria though. Look up something like 'how to sort dictionary keys python'. – AsheKetchum Sep 08 '17 at 17:47
  • Because the keys order in a dictionary is established based on the keys hashes that are computed on keys. The hash func is internal and subject to change between _Python_ releases. – CristiFati Sep 08 '17 at 19:13

2 Answers2

0

please sorted dict key for deterministic order.

dict1={'s':1,'a':2}
print(sorted(dict1.keys()))
Dharmesh Fumakiya
  • 2,276
  • 2
  • 11
  • 17
0

dict is not guaranteed to have ordered keys. If you need to retrieve keys in specific order, use OrderedDict from collections.

>>> b = OrderedDict([('k1','v1'),('k2','v2')])
>>> b.keys()
['k1', 'k2']
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175