I wrote this code to perform as a simple search engine in a list of strings like the example below:
mii(['hello world','hello','hello cat','hellolot of cats']) == {'hello': {0, 1, 2}, 'cat': {2}, 'of': {3}, 'world': {0}, 'cats': {3}, 'hellolot': {3}}
but I constantly get the error
'dict' object has no attribute 'add'
how can I fix it?
def mii(strlist):
word={}
index={}
for str in strlist:
for str2 in str.split():
if str2 in word==False:
word.add(str2)
i={}
for (n,m) in list(enumerate(strlist)):
k=m.split()
if str2 in k:
i.add(n)
index.add(i)
return { x:y for (x,y) in zip(word,index)}
The "AttributeError: 'dict' object has no attribute" means that we are trying to access an attribute or call a method on a dictionary that is not implemented by the dict class.
Conclusion # The Python "AttributeError: 'list' object has no attribute 'add'" occurs when we access the add attribute on a list. Use the append() or insert() methods to add an element to a list. If you have a list of set objects, access the list at a specific index before calling add() .
According to python documentation object. __dict__ is A dictionary or other mapping object used to store an object's (writable) attributes. Or speaking in simple words every object in python has an attribute which is denoted by __dict__. And this object contains all attributes defined for the object.
In Python, when you initialize an object as word = {}
you're creating a dict
object and not a set
object (which I assume is what you wanted). In order to create a set, use:
word = set()
You might have been confused by Python's Set Comprehension, e.g.:
myset = {e for e in [1, 2, 3, 1]}
which results in a set
containing elements 1, 2 and 3. Similarly Dict Comprehension:
mydict = {k: v for k, v in [(1, 2)]}
results in a dictionary with key-value pair 1: 2
.
x = [1, 2, 3] is a literal that creates a list (mutable array).
x = [] creates an empty list.
x = (1, 2, 3) is a literal that creates a tuple (constant list).
x = () creates an empty tuple.
x = {1, 2, 3} is a literal that creates a set.
x = {} confusingly creates an empty dictionary (hash array), NOT a set, because dictionaries were there first in python.
Use
x = set() to create an empty set.
Also note that
x = {"first": 1, "unordered": 2, "hash": 3} is a literal that creates a dictionary, just to mix things up.
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