python输出字典的问题

来源:百度知道 编辑:UC知道 时间:2024/09/22 03:53:14
自己写的小程序想按字典的值排序字典的键值,但是出问题了,程序如下:
seq = ['a', 'hello', 'hello', 'hello', 'hello', 'hello', 'hello', 'world', 'z', 'world', 'world', 'z']

count = {}

for x in seq:
if x not in count.keys():
count[x] = 1
else:
count[x] += 1

res = []
while len(count)!=0:
min = 999
for x in count.keys():
if count.get(x)<min:
min=count[x]
tempKey=x

res.append(tempKey)
count.pop(tempKey)

temp = [(key, count[key]) for key in res]

显示的是:
Traceback (most recent call last):
File "F:\workspace\eclipse for Python\Collective Intelligence\src\aa.py", line 30, in <module>
temp = [(key, count[key]) for key in res]
KeyError: 'a'
不知道要怎么改,麻烦帮

count.pop(tempKey) 这句不对

你把count清空了
把"count.pop(tempKey)"这一句去掉就应该OK了

dict.pop的用法如下
pop(key[, default])
If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.

PS: 其实有更简单的办法
seq = ['a', 'hello', 'hello', 'hello', 'hello', 'hello', 'hello', 'world', 'z', 'world', 'world', 'z']
keySet = set(seq)
temp = [(a, seq.count(a)) for a in keySet]
temp.sort(lambda x,y: cmp(x[1],y[1]))