0

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.

LtWorf
  • 7,286
  • 6
  • 31
  • 45
Atul Arvind
  • 16,054
  • 6
  • 50
  • 58
  • @LevLevitsky I had used the same question to resolve my issue, I am asking about why dictionary are always unsorted, if I add value in sorted manner. so its not duplicate one.:) – Atul Arvind Feb 10 '13 at 10:13

2 Answers2

3

Dictionaries are unsorted. They're just mappings between keys and values.

If you want a sorted dictionary, use collections.OrderedDict:

>>> import collections
>>> d = collections.OrderedDict(sorted_x)
>>> d
    OrderedDict([('c', 1), ('a', 2), ('b', 3)])
>>> d['c']
    1
Blender
  • 289,723
  • 53
  • 439
  • 496
  • yes! its possible to sort dictionary using this way, but I am asking about why dictionary are always unsorted, if I add value in sorted manner. – Atul Arvind Feb 10 '13 at 10:11
  • because are hash maps. This guarantees a fast lookup ( O(1) ). They are just mapping between keys and values, as blender already said. The implementation does not preserve the order, so it does not matter in which way you add values to them – Ant Feb 10 '13 at 10:38
2

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.

LtWorf
  • 7,286
  • 6
  • 31
  • 45