Skip to main content
 首页 » 编程设计

python: 'dict' 对象没有属性 'has_key'

2025年05月04日15thcjp

我有这段代码:

def separate_sets(self): 
    self.groups = {} 
    self.group_names = list(set(self.y)) 
    if len(self.group_names) > 2: 
        print ('more than two classes provided...exiting') 
        sys.exit() 
    #putting all the samples in a regular order so that their 
    #grouping can be easier. 
    combined  = sorted(zip(self.x, self.y), key = lambda n: n[1]) 
    #--doing val,key here because (x,y) was zipped 
    for val,key in combined: 
        if self.groups.has_key(key): 
            self.groups[key].append(val) 
        else: 
            self.groups[key] = [] 
            self.groups[key].append(val) 
    #train on each group 
    self.train() 

我收到以下错误消息:

if self.groups.has_key(key):

AttributeError: 'dict' object has no attribute 'has_key'

请您参考如下方法:

在 Python 3.x 中,has_key() 被移除,参见 documentation .因此,你必须使用 in,这是 pythonic 方式:

if key in self.groups: