-1

I'm trying to sort this dictionary a by the key alphabetically. I'm looping through in order, but the dictionary c at the end isn't sorted. I don't understand how python assigns the order of the dictionary key. Why does it maintain the original order? and how do I sort by key alphabetically?

a={'BE': 1, 'BC': 2, 'BO': 3, 'BI': 4, 'BK': 5, 'AQ': 6, 'AS': 7, 'BQ': 8, 'AW': 9, 'AY': 10}

b=sorted(a)

c={}
for i in b:
    print i
    c[i]=a[i]

I'm using python 2.7

jason
  • 3,811
  • 18
  • 92
  • 147

1 Answers1

0

In general, dictionaries/hashtables/hashmaps are unordered. To sort it, you might want to first convert it into a list of tuples or something ordered, then sort on that

As of python3.7 dictionaries are now insertion-ordered

IanQ
  • 1,831
  • 5
  • 20
  • 29
  • the obvious choice would be [OrderedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict)... – hiro protagonist Dec 23 '18 at 18:21
  • "An OrderedDict is a dict that remembers the order that keys were first inserted" sooooo you'd still need to get it sorted first...? – IanQ Dec 23 '18 at 18:22
  • you'd need to loop over the sorted keys and then insert into the `OrderedDict`. the result should be something dict-like i figured. or did i misunderstand? – hiro protagonist Dec 23 '18 at 18:24
  • You have served only the appetiser here. People are expecting a 3 course dinner. – cs95 Dec 23 '18 at 18:28