0

I have write down a simple code to sort a dictionary,

D1 = {2:3, 1:89, 4:5, 3:0}
sort_dic = {}
print sorted(D1)
for i in sorted(D1):
    sort_dic.update({i:D1[i]})
print sort_dic

Which works fine and generates desired output:

{1: 89, 2: 3, 3: 0, 4: 5}

but when, I have changed the dictionary, It won't work and never sorting the dictionary, showing a strange behavior without invoking an error:

 D1 = {307: 'LYS', 309: 'ARG', 86: 'GLU', 88: 'VAL', 92: 'ASN', 61: 'ILE', 111: 'ARG'}
 sort_dic = {}
 print sorted(D1)
 for i in sorted(D1):
      sort_dic.update({i:D1[i]})
 print sort_dic

result with this:

{307: 'LYS', 309: 'ARG', 86: 'GLU', 88: 'VAL', 92: 'ASN', 61: 'ILE', 111: 'ARG'}

thanks for help

Update: Thanks for the code but in this case my main concern Is to understand the distinct behavior of a code with two different dictionaries. Why its happening. Kindly, explain.

jax
  • 3,927
  • 7
  • 41
  • 70
  • Why do you want your dictionary to be sorted? – Elmex80s Mar 02 '17 at 11:38
  • I don't need any code rather in this case my main concern Is to understand the distinct behavior of a code with two different dictionaries. Why its happening. Kindly, explain. – jax Mar 02 '17 at 11:42

1 Answers1

2

You can't rely on dictionaries to remain in any particular order. Instead you should use an OrderedDict.

from collections import OrderedDict

sorted_dict = OrderedDict(sorted(D1.items(), key=lambda t: t[0]))

An OrderedDict remembers it's insertion order, so when you add new entries you will need to sort it again, unless you know that the new entries belong at the "end" of your dictionary.

Tim B
  • 3,033
  • 1
  • 23
  • 28
  • Update: Thanks for the code but in this case my main concern Is to understand the distinct behavior of a code with two different dictionaries. Why its happening. Kindly, explain. – jax Mar 02 '17 at 11:40
  • 1
    @jax unless you use an OrderedDict the order of items in a dictionary can change at any point. This is typical of dictionaries in many languages. – Tim B Mar 02 '17 at 11:43
  • Ok, so we cant control the order of a dictionary without putting an extra force like "OrderedDict" :) – jax Mar 02 '17 at 11:47
  • @jax That's right, you need the OrderedDict to achieve this. If this answers your question please "accept" this answer (the tick mark under the voting arrows). – Tim B Mar 02 '17 at 11:48
  • just for the sake of my curiosity, why did dictionary in the first case able to maintain its order but not in second case. – jax Mar 02 '17 at 12:02
  • 1
    @jax cf http://stackoverflow.com/questions/15479928/why-is-the-order-in-dictionaries-and-sets-arbitrary – bruno desthuilliers Mar 02 '17 at 12:12