La Murga
La Murga

Reputation: 303

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 have read already several forums and most of them suggest using OrderedDict(). But as explained here:

Python OrderedDict not keeping element order

OrderedDict(dict) will not keep the order when the dictionary is written in that form. I can not manually create the dictionary in an specific way (e.g list of tuples) because it is randomly generated by the code elsewhere. Thank you very much for you help!!

Upvotes: 4

Views: 3235

Answers (3)

Rodrigo Saraguro
Rodrigo Saraguro

Reputation: 1

Just use 2 for:

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

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

Upvotes: 0

Emmett Butler
Emmett Butler

Reputation: 6207

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)

Upvotes: 1

sashkello
sashkello

Reputation: 17871

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.

Upvotes: 3

Related Questions