Ordered Dictionary in Python

后端 未结 3 2128
夕颜
夕颜 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)
    

提交回复
热议问题