2015-08-19 28 views
5

ho seguito strutturaOrdinamento dizionario nidificato nel dizionario Python

{ 
    'searchResult' : [{ 
      'resultType' : 'station', 
      'ranking' : 0.5 
     }, { 
      'resultType' : 'station', 
      'ranking' : 0.35 
     }, { 
      'resultType' : 'station', 
      'ranking' : 0.40 
     } 
    ] 
} 

e voglio ottenere

{ 
    'searchResult' : [{ 
      'resultType' : 'station', 
      'ranking' : 0.5 
     }, { 
      'resultType' : 'station', 
      'ranking' : 0.4 
     }, { 
      'resultType' : 'station', 
      'ranking' : 0.35 
     } 
    ] 
} 

provato il codice senza successo

result = sorted(result.items(), key=lambda k: k[1][0][1]["ranking"], reverse=True) 
+0

Grazie a tutti! Ma quale metodo è più veloce 'd [" elemento "]. Sort()' o 'sorted()'? – SpanishBoy

+1

possibile duplicato di [Come faccio a ordinare una lista di dizionari in base ai valori del dizionario in Python?] (Http://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries -by-values-of-the-dictionary-in-python) – PyNEwbie

+0

@SpanishBoy 'sorted' restituisce un nuovo oggetto. Se non hai bisogno dell'oggetto originale, è meglio che tu scelga 'sort' per la velocità e l'efficienza della memoria. –

risposta

5

Se si sta bene con il cambiamento gli oggetti sul posto.

a = { 
    'searchResult' : [{ 
         'resultType' : 'station', 
         'ranking' : 0.5 
         }, { 
         'resultType' : 'station', 
         'ranking' : 0.35 
         }, { 
         'resultType' : 'station', 
         'ranking' : 0.40 
         }] 
    } 

a["searchResult"].sort(key=lambda d: d["ranking"], reverse=True) 

Oppure si può fare una copia profonda per mantenere l'originale

from copy import deepcopy 


srt_dict = deepcopy(a) 
srt_dict["searchResult"].sort(key=lambda d: d["ranking"], reverse=True) 
2

Si può solo ordinare la lista e scrivere su se stessa nel dizionario.

result = { 
    'searchResult' : [{ 
      'resultType' : 'station', 
      'ranking' : 0.5 
     }, { 
      'resultType' : 'station', 
      'ranking' : 0.35 
     }, { 
      'resultType' : 'station', 
      'ranking' : 0.40 
     } 
    ] 
} 

result['searchResult'] = sorted(result['searchResult'], key= lambda x: x['ranking'], reverse=True) 
5

si può semplicemente fare una sorta inplace sulla lista, utilizzando key=itemgetter("ranking") e reverse=True:

from operator import itemgetter 
d["searchResult"].sort(key=itemgetter("ranking"),reverse=True) 

print(d) 
{'searchResult': [{'resultType': 'station', 'ranking': 0.5}, {'resultType': 'station', 'ranking': 0.4}, {'resultType': 'station', 'ranking': 0.35}]}