I have a dictionary like
>>> x = {'a':2, 'c': 1, 'b':3}
There is no method available in dictionary to sort the dictionary by value. I sorted it using
>>> sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
>>> sorted_x
[('c', 1), ('a', 2), ('b', 3)]
but now when I convert to sorted_x to dictionary again by using loop. like
>>> new_dict = {}
>>> for i in sorted_x:
new_dict[i[0]] = i[1]
>>> new_dict
{'a': 2, 'c': 1, 'b': 3}
The new_dict again remains unsorted. Why the python dictionary cannot be sorted by key? can anyone shed light on it.
Dictionaries in python are hash maps. The keys are hashed in order to keep a fast access to the elements.
This means that internally the elements must be ordered depending on the hash they generate, not depending on the order you want to give.