-1

I have a hashtable and a lambda for sort like this:

 h = {"hlllleleo": 9, "hello": 5, "fgfgggf" : 7, "abcdefgh": 8}
 lbda = lambda x : h[x]
 from collections import OrderedDict as od
 od({x:h[x] for x in sorted(h, key=lbda)})
 #Outputs:
 OrderedDict([('abcdefgh', 8), ('hlllleleo', 9), ('fgfgggf', 7), 
 ('hello', 5)])

Why is the ordered dict not coming out sorted as it is built? If I loop over sorted() it is sorted:

 for x in sorted(h, key=lbda):
   print x, h[x]

 # Outputs:
 hello 5
 fgfgggf 7
 abcdefgh 8
 hlllleleo 9
user2399453
  • 2,930
  • 5
  • 33
  • 60

1 Answers1

3

The reason is simple. You sort the dictionary by keys, and create a new dictionary using a comprehension. However, by the time the dictionary is created and passed to the OrderedDict constructor for creation, it has already forgotten the order.

Let's convert your dict comprehension into a list comprehension:

In [413]: [(x, h[x]) for x in sorted(h, key=lambda x : h[x])]
Out[413]: [('hello', 5), ('fgfgggf', 7), ('abcdefgh', 8), ('hlllleleo', 9)]

And now, the same thing with a dictionary:

In [414]: {x : h[x] for x in sorted(h, key=lambda x : h[x])}
Out[414]: {'abcdefgh': 8, 'fgfgggf': 7, 'hello': 5, 'hlllleleo': 9}

As you can see, the dictionary you generate bears no resemblance to the list comprehension in terms of ordering, since the generated dict has already forgotten its ordering.

cs95
  • 379,657
  • 97
  • 704
  • 746