I have bumped on unclear dict sorting behavior in Python. Assuming that I have following dict:
m_dict = {"a":4, "b":3, "c":2, "d":1}
And I’d like to sort it by the value:
a = sorted(m_dict.items(), key=lambda x: x[1], reverse=True)
b = sorted(m_dict.items(), key=lambda x: x[1], reverse=False)
That works as expected. However, when I convert it back to the dictionary:
a1 = dict(sorted(m_dict.items(), key=lambda x: x[1], reverse=True))
b1 = dict(sorted(m_dict.items(), key=lambda x: x[1], reverse=False))
both dictionaries have the same content, which is not what I expect, as I expect them have the same order as in a and b.
Any ideas what is the root cause?
I have actually looked at How do I sort a dictionary by value? and this question stems from that post
R.P. McMerphy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
4