2017-04-02 88 views
0
counts = {'A1':3,'A2':2,'A3':1,'A4':10,'B1':11,'B2':12,'B3':3,'B4':0,'C1':3,'C2':16,'C3':8,'C4':2} 


#Order grid 
def orderGrid(grid): 

    lst = list() 
    for key,val in grid.items(): 
     lst.append((val,key)) 

    lst.sort(reverse=True) 

    for val,key in lst: 
     print key, val 

#Order row 
def orderRow(row): 
    count = dict() 
    for key in row.items(): 
     if key[0] not in count: 
      count[key] = row[key] 
     else: 
      count[key] += row[key] 
    print 'A:', count 

orderGrid功能可以運行成功計算出它的價值,但由於orderrow功能對於集羣中的所有金額,從「A」開始,然後排名行( 'A', 'B', 'C', 'd')如何獲得所有相同的「鍵[0]」,並在字典

+0

什麼是你想要的輸出? – manvi77

+0

@ manvi77 like,{A-row:16,B-row:26 ...} – hsbzzhz

回答

0

您可以使用sorted並直接在counts

import operator 

sorted_x = sorted(counts.items(), key=operator.itemgetter(1), reverse=True) 

應用可以採取一種新的dict和分配的關鍵,值如下:

In [71]: mydict = {} 

In [72]: for k, v in counts.items(): 
    ...:  if k[0] not in mydict: 
    ...:   mydict[k[0]] = v 
    ...:  else: 
    ...:   mydict[k[0]] += v 
    ...:   

In [73]: mydict 
Out[73]: {'A': 16, 'B': 26, 'C': 29} 

更換功能是這樣的,

import operator 

counts = {'A1':3,'A2':2,'A3':1,'A4':10,'B1':11,'B2':12,'B3':3,'B4':0,'C1':3,'C2':16,'C3':8,'C4':2} 


#Order grid 
def orderGrid(grid): 
    sorted_x = sorted(counts.items(), key=operator.itemgetter(1), reverse=True) 
    for key,val in sorted_x: 
     print key, val 

#Order row 
def orderRow(row): 
    mydict = {} 
    for k, v in row.items(): 
     if k[0] not in mydict: 
      mydict[k[0]] = v 
     else: 
      mydict[k[0]] += v 
    print mydict 
相關問題