2011-11-07 3 views
37

Sto cercando di ordinare OrderedDict in OrderedDict tramite chiave 'depth'. C'è qualche soluzione per ordinare quel dizionario?Come ordinare OrderedDict of OrderedDict - Python

OrderedDict([ 
    (2, OrderedDict([ 
    ('depth', 0), 
    ('height', 51), 
    ('width', 51), 
    ('id', 100) 
    ])), 
    (1, OrderedDict([ 
    ('depth', 2), 
    ('height', 51), 
    ('width', 51), 
    ('id', 55) 
    ])), 
    (0, OrderedDict([ 
    ('depth', 1), 
    ('height', 51), 
    ('width', 51), 
    ('id', 48) 
    ])), 
]) 

dict Ordinati dovrebbe assomigliare a questa:

OrderedDict([ 
    (2, OrderedDict([ 
    ('depth', 0), 
    ('height', 51), 
    ('width', 51), 
    ('id', 100) 
    ])), 
    (0, OrderedDict([ 
    ('depth', 1), 
    ('height', 51), 
    ('width', 51), 
    ('id', 48) 
    ])), 
    (1, OrderedDict([ 
    ('depth', 2), 
    ('height', 51), 
    ('width', 51), 
    ('id', 55) 
    ])), 
]) 

alcuna idea di come ottenerlo?

risposta

67

È necessario crearne uno nuovo poiché OrderedDict è ordinato per ordine di inserzione.

Nel tuo caso il codice sarebbe simile a questa:

foo = OrderedDict(sorted(foo.iteritems(), key=lambda x: x[1]['depth'])) 

Vedere http://docs.python.org/dev/library/collections.html#ordereddict-examples-and-recipes per ulteriori esempi.

+2

Ciò causerà un'eccezione se qualsiasi dict non ha 'profondità' come chiave. Questo potrebbe essere desiderato. Se non lo è, puoi assumere una chiave predefinita usando "get". – TomOnTime

+5

Nota che '[1]' qui si riferisce ai valori di foo, al contrario dei suoi tasti, che sarebbe '[0]' – emisilva

15
>>> OrderedDict(sorted(od.items(), key=lambda item: item[1]['depth']))