4

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!!

Community
  • 1
  • 1
La Murga
  • 303
  • 4
  • 15
  • If your dictionary is "randomly generated by the code elsewhere", then what order are you trying to preserve exactly? You've lost any concept of ordering in "the code elsewhere". In other words, "keep the order of this dictionary" makes no sense - a dictionary is **not ordered**. – isedev Mar 14 '14 at 00:12
  • 2
    Don't name your variable with the name of a type, i.e. don't call it `dict`. – metatoaster Mar 14 '14 at 00:16

3 Answers3

3

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.

sashkello
  • 17,306
  • 24
  • 81
  • 109
  • 1
    Note as of python 3.7, dict are insertion ordered, per this answer https://stackoverflow.com/a/39980744/6049173 – HHest Sep 29 '22 at 13:34
1

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)
Emmett Butler
  • 5,969
  • 2
  • 29
  • 47
0

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])