Skip to content Skip to sidebar Skip to footer

Ordered Dictionary In Python

I have a Dictionary in Python such as this: dict = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1} Is there any way that I can keep the order of this dictionary expressed this way. I h

Solution 1:

The moment you write dict = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}, you already have lost the order of the elements. The ways to keep it:

a. Create OrderedDict from your data in the first place.

b. Convert your dict to a list of tuples and sort in a way you want, then create OrderedDict from it.

All in all, from your question it is not clear what you want to preserve. If it is generated "randomly" then who cares, if there is some logic behind it, then use this logic to recreate that order and create OrderedDict using it. If there is something happening behind the scenes which creates this dict from some input data, then, alas, the order in which you see it is not the order in which it has been created.

PS And don't call your dict dict.

Solution 2:

If the dictionary you want to order is created outside of your control, you might use the following to get its key:value pairs as a list of tuples:

pairs = my_dict.items()

You can then sort this list any way you like. When you've done that, you can pass the ordered list of pairs to the OrderedDict constructor

from collections import OrderedDict
# sort in some way (for example, reverse the key order)
pairs = reversed(my_dict.items())
ordered = OrderedDict(pairs)

Solution 3:

Just use 2 for:

dict = {'a':4, 'q':1, 'l':2, 'm':4, 'p':1}

i = max(dict.values())+1for el inrange (i):
    for letter indict:
        if el==dict[letter]:
            print(letter,dict[letter])

Post a Comment for "Ordered Dictionary In Python"