如
想对字典wordhash排序:
通过list实现:wordlist
wordhash={'ufeff': 1, '作者': 8, ':': 114, 'Calvin': 1, 'Shi': 1, '链接': 1, 'www': 1, '.': 35, 'zhihu': 1, 'question': 1, '27068465': 1} wordlist = [('ufeff', 1), ('Calvin', 1), ('Shi', 1), ('链接', 1), ('www', 1), ('zhihu', 1), ('question', 1), ('27068465', 1)]
item:item[1]代表是元组('Calvin', 1)中的第二个元素‘1’进行排序
reverse=False代表词频从小到大
wordhash = {} #字典的初始化 wordhash = cipin(content) wordlist = sorted(wordhash.items(),key=lambda item:item[1],reverse=False) for tuple in wordlist: word = tuple[0] print(word+' '+str(wordhash[word]))
判断某个key是否在字典中
def cipin(content): wordhash = {} words = content.split() for word in words: if word in wordhash: wordhash[word] += 1 else: wordhash[word] = 1 return wordhash