2012-10-25 24 views
7

voglio convertire un dict in dict ordinati in pitoneconvertire un dict per dict ordinato in python

data = pandas.read_csv('D:\myfile.csv') 
for colname, dtype in data.dtypes.to_dict().iteritems(): 
    if dtype == 'object': 
     print colname 
     count = data[colname].value_counts() 
     d = dict((str(k), int(v)) for k, v in count.iteritems()) 
     f = dict(sorted(d.iteritems(), key=lambda item: item[1], reverse = True)[:5]) 
     print f 

     m ={} 
     m["count"]= int(sum(count))  
     m["Top 5"]= f  
     print m  
     k = json.dumps(m) 
     print k  
f = {'Gears of war 3': 6, 'Batman': 5, 'gears of war 3': 4, 'Rocksmith': 5, 'Madden': 3} 

la mia uscita desiderata è:

f = {'Gears of war 3': 6, 'Batman': 5, 'Rocksmith': 5, 'gears of war 3': 4, 'Madden': 3} 
k = {'count':24, 'top 5':{'Gears of war 3': 6, 'Batman': 5, 'Rocksmith': 5, 'gears of war 3': 4, 'Madden': 3}} 

(in ordine decrescente di valori e la il risultato dovrebbe essere un ditt)

+1

Perché vuoi farlo, invece di avere solo una lista ordinata? – emschorsch

risposta

15

Non è possibile ordinare uno dict perché il dizionario non ha ordini.

Al contrario, utilizzare collections.OrderedDict:

>>> from collections import OrderedDict 
>>> d = {'Gears of war 3': 6, 'Batman': 5, 'gears of war 3': 4, 'Rocksmith': 5, 'Madden': 3} 

>>> od = OrderedDict(sorted(d.items(), key=lambda x:x[1], reverse=True)) 
>>> od 
OrderedDict([('Gears of war 3', 6), ('Batman', 5), ('gears of war 3', 4), ('Rocksmith', 5), ('Madden', 3)]) 

>>> od.keys() 
['Gears of war 3', 'Batman', 'gears of war 3', 'Rocksmith', 'Madden'] 
>>> od.values() 
[6, 5, 4, 5, 3] 
>>> od['Batman'] 
5 

L ' "ordine" che si vede in un oggetto JSON non è significativo, in quanto oggetto JSON è ordinata [RFC4267].

Se si desidera un ordinamento significativo nel proprio JSON, è necessario utilizzare un elenco (ordinato nel modo desiderato). Qualcosa di simile a questo è quello che ci vuole:

{ 
    "count": 24, 
    "top 5": [ 
    {"Gears of war 3": 6}, 
    {"Batman": 5}, 
    {"Rocksmith": 5}, 
    {"gears of war 3": 4}, 
    {"Madden": 3} 
    ] 
} 

Data la stessa dict d, è possibile generare un elenco ordinato (che è ciò che si vuole) da:

>>> l = sorted(d.items(), key=lambda x:x[1], reverse=True) 
>>> l 
[('Gears of war 3', 6), ('Batman', 5), ('Rocksmith', 5), ('gears of war 3', 4), ('Madden', 3)] 

Ora basta passare l a m['top5'] e scaricarlo:

m["Top 5"]= l 
k = json.dumps(m) 
+0

@emschorsch voglio aggiungere l'output dict a un altro dict e convertirlo in risposta json. –

+0

@emschorsch ho modificato il mio codice sopra, per favore, passa attraverso. –

+0

@CodeNinja Gli oggetti JSON non hanno ordine, quindi è necessario utilizzare una lista. –