I am using python 3.6.5 and I am sorting an OrderedDict
, e.g. tmp.py
:
from collections import OrderedDict
d = OrderedDict()
d[6] = 'a'
d[5] = 'b'
d[3] = 'c'
d[4] = 'd'
print(d)
print("keys : {}".format(d.keys()))
d = OrderedDict(sorted(d.items()), key=lambda t: t[1])
print(d)
print("keys : {}".format(d.keys()))
When I run tmp.py
, I get :
OrderedDict([(6, 'a'), (5, 'b'), (3, 'c'), (4, 'd')])
keys : odict_keys([6, 5, 3, 4])
OrderedDict([(3, 'c'), (4, 'd'), (5, 'b'), (6, 'a'), ('key', <function <lambda> at 0x2ab444506bf8>)])
keys : odict_keys([3, 4, 5, 6, 'key'])
Clearly the process of sorting has appended the key()
function to my new OrderedDict
. I believe that I am sorting this in the same fashion prescribed in this post.
QUESTION :
Why does this happen and how to I properly sort an OrderedDict
?