Ordered Dictionary in Python

后端 未结 3 2129
夕颜
夕颜 2020-12-21 02:07

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 diction

相关标签:
3条回答
  • 2020-12-21 02:29

    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)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-21 02:45

    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])
    
    0 讨论(0)
提交回复
热议问题