How to reorder a python ordered dict based on array?

前端 未结 2 2005
孤独总比滥情好
孤独总比滥情好 2021-01-04 18:52

Say I have an Ordered Dict with the following items:

mydict = {\'Rust\': {\'definition\':\'rusts definition\'}, \'Iron\': {\'definition:\'iron definition\'},         


        
相关标签:
2条回答
  • 2021-01-04 19:31

    Try this:

    mydict = {'Rust': {'definition':'rusts definition'},
              'Iron': {'definition':'iron definition'},
              'Pyrite': {'definition':'pyrite definition'}}
    
    myorder = ['Pyrite', 'Rust', 'Iron']
    
    from collections import OrderedDict
    
    ordered = OrderedDict()
    for k in myorder:
        ordered[k] = mydict[k]
    

    Or even shorter:

    ordered = OrderedDict((k, mydict[k]) for k in myorder)
    

    Using the above snippet, ordered will contain the same keys/values as mydict, but they'll be inserted in the same order specified by myorder. That's the advantage of OrderedDict: when iterating over it, it'll preserve the insertion order.

    There's no way to sort the existing dictionary in-place (well, you could extract all the key-value pairs, eliminate them and add them again in the correct order, but that's not the idea, is it?), it's necessary to create a new one ... or simply iterate over the existing dictionary in the specified order:

    for k in myorder:
        x = mydict[k] # do something with x
    
    0 讨论(0)
  • 2021-01-04 19:33

    If you would like to use them in that order, you can do this, for example.

    for key in myorder:
        value = mydict[key]
        print value
    

    Outputs:

    {'definition': 'pyrite definition'}
    {'definition': 'rusts definition'}
    {'definition': 'iron definiti
    
    0 讨论(0)
提交回复
热议问题