如何获得所有相同的'key [0]'并在字典中计算其值

时间:2017-04-02 04:58:22

标签: python dictionary cluster-computing

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')< / p>

1 个答案:

答案 0 :(得分: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