Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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'

like image 953
Sumin Jeong Avatar asked Oct 11 '17 00:10

Sumin Jeong


People also ask

Does Iteritems have no attribute?

The Python "AttributeError: 'dict' object has no attribute 'iteritems'" occurs because the iteritems() method has been removed in Python 3. To solve the error, use the items() method, e.g. my_dict. items() , to get a view of the dictionary's items.

What is a dict object in Python?

Dictionary. Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and do not allow duplicates. As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

Does Python have key 3?

Python 3 - dictionary has_key() Method The method has_key() returns true if a given key is available in the dictionary, otherwise it returns a false.


3 Answers

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:
like image 105
Óscar López Avatar answered Nov 03 '22 00:11

Óscar López


In python you could use "in" to check

 if key in self.groups:
like image 23
galaxyan Avatar answered Nov 03 '22 01:11

galaxyan


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

    self.groups.setdefault(key, []).append(val)
like image 29
chepner Avatar answered Nov 02 '22 23:11

chepner