0

When we print values in a dictionary, is there any default sorting that use to print the keys and values in a Python dictionary? Or do they randomly print the key , value pairs?

Please see below code. is there any order of dictionary value print in python?

confusion = {}

confusion[1] = 1
confusion[4] = 22
confusion['5'] = 2
confusion['2'] = 2
confusion[1.0] = 4
confusion['1'] = 2

print confusion

The result is {'2': 2, 1: 4, '1': 2, '5': 2, 4: 22}

newday
  • 3,842
  • 10
  • 54
  • 79

3 Answers3

1

Use collections.OrderedDict if you want to have the insertion order maintained. By default, python's dict does not maintain the order.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
venpa
  • 4,268
  • 21
  • 23
1

No, dictionaries are by definition unordered. What you see here might change from version to version and platform to platform

Eric
  • 19,525
  • 19
  • 84
  • 147
0

Quoting the documentation:

CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

nobody
  • 19,814
  • 17
  • 56
  • 77