python对字符串统计出现次数位列前3的字符

例如输入:
hello world abcaafgaa
输出:
5:a
3:l
2: ,o


s=input()
dict={}
for i in s:
    dict[i]=s.count(i)
count=0
temp=-1
for j in sorted(dict.values(),reverse=True):
    if j!=temp:
        temp=j
    else:
        continue
    print(j,":",sep="",end="")
    l=[]
    for k in dict:
        if dict[k]==j:
            l.append(k)
    print(",".join(sorted(l)))
    count+=1
    if count==3:
        break

是这样吗?


str1 = input()
data1 = {}
data2 = {}
for i in str1:
    data1[i] = str1.count(i)
x = 3
while(x):
    t=max(data1,key=data1.get)
    data2[t] = data1[t]
    data1.pop(t)
    x -= 1
for key in data2:
    print(data2[key],':',key)