简体   繁体   中英

How to get all same 'key[0]' and calculate its value in the dictionary

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 function can run successful, but as the orderrow function is for cluster All amount, which start from 'A', and then rank the rows ('A','B','C','D')

You can use sorted and apply directly on counts

import operator

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

You can take a new dict and assign key, values as follows:

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}

Replacing the functions would look like this,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM