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'
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.
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.
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.
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:
In python you could use "in" to check
if key in self.groups:
You can eliminate the whole if
statement by using the setdefault
method
self.groups.setdefault(key, []).append(val)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With