0

Possible Duplicate:
Python: Sort a dictionary by value

I am trying to sort a dictionary by its values using sorted(data.items(),key=operator.itemgetter(1))

I manage to sort the values correctly, but I get a list not a dictionary.

Could sb tell me how to sort my dictionary saving dictionary type?

thanks!

Community
  • 1
  • 1
user1287285
  • 11
  • 1
  • 5

2 Answers2

4

Dictionary entries are not ordered. If you want the key-value pairs to be ordered, use a collections.OrderedDict.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • I cannot import that module, i am using python-2.6.1 – user1287285 Mar 31 '12 at 18:23
  • 1
    @user: [`sudo pip install ordereddict`](http://stackoverflow.com/questions/1617078/ordereddict-for-older-versions-of-python). Also: What's the particular problem you are trying to solve here? Is it about presenting something to the user? – Niklas B. Mar 31 '12 at 18:23
  • @user1287285: The link in my answer also points to a drop-in substitute [for Python 2.4 or greater](http://code.activestate.com/recipes/576693/). – unutbu Mar 31 '12 at 18:54
0

As stated before many times, dictionaries can't be sorted.

If you need your dictionary to be sorted for commands such as dict.keys() or dict.values(), use sorted(dict.keys()) or sorted(dict.values()) instead.

If you don't want to do that, the only other option is to use a 2d array, where the format is:

((key, value), (key1, value1), (key2, value2), etc.)
beary605
  • 802
  • 2
  • 9
  • 18