Search code examples
pythondictionaryordereddictionary

How to order a dictionary by the key alphabetically


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?


Solution

  • 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.