Sumin Jeong
Sumin Jeong

Reputation: 81

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

I have this piece of code:

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

And I received the following error message:

if self.groups.has_key(key):

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

Upvotes: 7

Views: 17538

Answers (4)

chepner
chepner

Reputation: 531055

You can eliminate the whole if statement by using the setdefault method

    self.groups.setdefault(key, []).append(val)

Upvotes: 2

Victor Castillo Torres
Victor Castillo Torres

Reputation: 10811

As of python 3.x has_key was removed, now you have to use the in operator

Upvotes: 0

Óscar López
Óscar López

Reputation: 236004

In Python 3.x, has_key() was removed, see the documentation. Hence, you have to use in, which is the pythonic way:

if key in self.groups:

Upvotes: 16

galaxyan
galaxyan

Reputation: 6111

In python you could use "in" to check

 if key in self.groups:

Upvotes: 4

Related Questions