Python字典的排序

已知所需要处理的字典:person = {'ann':100,'lili':98,'mary':85, 'tom':47,'kate':87,'dave':79,'sue':85,'john':71,'jim':56,'allen':90}

1,求最大的分数和名字。

2,平均分数

3,根据分数排序(如果分数一样,根据名字)

4,给每一个人一个等地((A:90 above,B:80~89,C:60~80,D:below 60))



#! usr/bin/python

# -*- coding:utf-8 -*-

#由于对于python的dirction不是熟练应用,一开始做的很繁琐。

#1,求最大的分数和名字。

person = {'ann':100,'lili':98,'mary':85,'tom':47,'kate':87,'dave':79,'sue':85,'john':71,'jim':56,'allen':90}

values=person.values()

keys=person.keys()

values.sort()

maxvalue=values[-1]

for i in keys:

    if person[i] == maxvalue :

        maxkey=i

print 'Max score and name is :',maxvalue,maxkey



#2,平均分数

sum=0

average=0

for j in values:

    sum+=j

    average=sum/len(values)

print "Average score:",average



3,根据分数排序(如果分数一样,根据名字)

array1=[]

for i in range(len(values)):

    max=i

    for j in range(i+1,len(values)):

        if values[j]>values[max]:

            max=j

    values[i],values[max]=values[max],values[i]

    array1.append(values[i])

print 'array1:',array1

for l in range(len(array1)-2):

    if array1[l]==array1[l+1]:

        del array1[l]

print 'after del,array1:',array1

values=person.values()

array2=[]

for x in range(len(array1)):

    for y in range(len(values)):

        if array1[x]==values[y]:

            array2.append(y)

print 'array2',array2

for i in array2:

    print 'Sort the name by the score :%-10s%-10d'%(keys[i],values[i])

后来,找了资料python dict按照key 排序,于是会更加简单。

sorted(person.items(),lambdax, y: cmp(x[1], y[1]))


4,给每一个人一个等地((A:90 above,B:80~89,C:60~80,D:below 60))

keys=person.keys()

values=person.values()

A=[]

B=[]

C=[]

D=[]

for i in range(len(values)):

    if values[i]>=90:

        A.append(i)

    elif 80<=values[i]<=89:

        B.append(i)

    elif 60<=values[i]<79:

        C.append(i)

    else:

        D.append(i)

for a in 'A' :

        print "A:",keys[a]

for b in 'B':

        print "B:",keys[b]

for c in'C':

        print "C:",keys[c]

for d in'D':

        print "D:",keys[d]

你可能感兴趣的:(Python字典的排序)