1
from collections import OrderedDict
dictionary = {"Charlie": [[7]], "Alex": [[4]], "Brandon": [[8]]}
OrderedDict(sorted(dictionary.items(), key=lambda x: x[0]))
print(dictionary)

Okay I am trying to order my dictionary by the key, in alphabetical order, but the dictionary doesn't change order after the 3rd line of code as seen above. Can anyone help me with a solution?

Flux
  • 25
  • 8
  • possible duplicate of [How to sort dictionary by key in alphabetical order Python](http://stackoverflow.com/questions/22264956/how-to-sort-dictionary-by-key-in-alphabetical-order-python) – Nir Alfasi Jan 20 '15 at 19:26
  • Also duplicate of this: http://stackoverflow.com/questions/9001509/python-dictionary-sort-by-key (I actually like the answers better) – moooeeeep Jan 20 '15 at 20:06

3 Answers3

3

OrderedDict is not a function which orders dictionaries. That is impossible since dictionaries are naturally unordered in Python. Instead, OrderedDict is a special kind of dictionary that supports ordered items.

If you want to use an OrderedDict in your code, you will need to save it in a variable:

ordered_dict = OrderedDict(sorted(dictionary.items(), key=lambda x: x[0]))

Note however that dictionary will still be unordered after this operation; the line above only uses the items in dictionary to construct a new OrderedDict object.

1

You will have to assign it back to dictionary as it is not in-place

dictionary = OrderedDict(sorted(dictionary.items(), key=lambda x: x[0]))

Now your o/p will be as expected

OrderedDict([('Alex', [[4]]), ('Brandon', [[8]]), ('Charlie', [[7]])])
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
1

You dont need key for your sorted function :

>>> OrderedDict(sorted(dictionary.items()))
OrderedDict([('Alex', [[4]]), ('Brandon', [[8]]), ('Charlie', [[7]])])
Mazdak
  • 105,000
  • 18
  • 159
  • 188