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,730
  • 9
  • 50
  • 77

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
  • 56,349
  • 8
  • 83
  • 124
venpa
  • 4,060
  • 19
  • 23
1

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

Eric
  • 19,040
  • 18
  • 80
  • 143
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,421
  • 17
  • 55
  • 76