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
  • 55,207
  • 16
  • 142
  • 150

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,188
  • 6
  • 12