蟒蛇:' dict'对象没有属性' has_key'

时间:2017-10-11 00:34:46

标签: python

我有这段代码:

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()

我收到以下错误消息:

  

如果self.groups.has_key(key):

     

属性错误:' dict'对象没有属性' has_key'

4 个答案:

答案 0 :(得分:6)

在Python 3.x中删除了has_key(),请参阅documentation。因此,你必须使用in,这是pythonic方式:

if key in self.groups:

答案 1 :(得分:3)

在python中你可以使用“in”来检查

 if key in self.groups:

答案 2 :(得分:1)

您可以使用if方法

删除整个setdefault语句
    self.groups.setdefault(key, []).append(val)

答案 3 :(得分:0)

python 3.x has_key was removed开始,现在你必须使用in运算符