7

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'

1
  • 1
    What about the error is not clear? has_key was deprecated. Are you using Python 3 by any chance? Commented Oct 11, 2017 at 0:37

4 Answers 4

16

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:
Sign up to request clarification or add additional context in comments.

Comments

4

In python you could use "in" to check

 if key in self.groups:

Comments

2

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

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

2 Comments

oh, you mean the whole 'if' to 'else' ?
Yes. setdefault returns a reference to self.groups[key], or [] if key isn't in the dict. Either way, you can then add val to the resulting list.
0

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

2 Comments

Did you not see the other 2 answers with identical content?
@cᴏʟᴅsᴘᴇᴇᴅ posted same time as the Óscar López answer ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.