Python 3.0 替代 Python 2.0 的 `.has_key` 函数

2 投票
1 回答
2648 浏览
提问于 2025-04-17 23:11

我的程序在Python 2.0上能正常运行,但我需要它在3.0或更高版本上也能工作。问题是新版本的Python不再有.has_key这个功能了。我需要知道怎么解决这个问题,让它在新版本上也能用。

dictionary = {}

for word in words:
    if dictionary.has_key(word):
        dictionary[word]+=1
    else:
        dictionary[word]=1
bonus = {}
for key in sorted(dictionary.iterkeys()):
    print("%s: %s" % (key,dictionary[key]))
    if len(key)>5: #if word is longer than 5 characters (6 or greater) save to list, where we will get top 10 most common
        bonus[key]=dictionary[key]

1 个回答

5

使用 in 来检查键是否存在:

if word in dictionary:

并把 .iterkeys() 替换成 .keys();在这种情况下,直接用 sorted(dictionary) 就可以了(在 Python 2 和 3 中都适用)。

你的代码可以稍微简化一下,使用更现代的写法,把 dictionary 替换成一个 collections.Counter() 对象:

from collections import Counter

dictionary = Counter(words)

bonus = {}
for key in sorted(dictionary):
    print("{}: {}".format(key, dictionary[key]))
    if len(key) > 5:
        bonus[key] = dictionary[key]

不过你也可以使用 Counter.most_common() 来按频率(从高到低)列出键。

如果你是把代码从 Python 2 转到 3,建议你看看 Python 迁移指南

撰写回答