0

I am trying to add elements to a dictionary in the following way:

a = {}
a['b'] = 1
a['a'] = 2

Finally a looks like:

{'a': 2, 'b': 1}

But actually I wanted the dictionary to contain keys in the order:

{'b': 1, 'a': 2}

Can anyone explain me this? Why are the keys getting sorted alphabetically when actually dictionaries (hashmaps) don't have any order?

styvane
  • 59,869
  • 19
  • 150
  • 156

1 Answers1

1

You are correct in that dictionaries are not ordered, but hashed. As a result, the order of a dictionary should not be relied on.

You can use the OrderedDict to help you achieve your goal:

from collections import OrderedDict
a = OrderedDict()
a['b'] = 1
a['a'] = 2

 > a
 > OrderedDict([('b', 1), ('a', 2)])
AbrahamB
  • 1,348
  • 8
  • 13