The def add(self, tag)
is saying that the add
method takes a tag
parameter. So you call the method like this:
myTagCloud.add('Hello')
In this example, 'Hello'
is passed in as the tag
parameter. Then inside the add
method, wherever you see tag
, it’s actually working with 'Hello'
.
So this…
self.tags[tag.lower()]
Becomes…
self.tags['Hello'.lower()]
Which becomes…
self.tags['hello']
The reason for the []
is that self.tags
is a dictionary, and to find an item in a dictionary, you look up the item by its key. The thing in the []
is the key. So let’s say we have a dictionary that looks like this:
myDictionary = {
'hello': 2,
'world': 1
}
This is a dictionary with two entries. The first entry is referred to by the key 'hello'
and the second entry is referred to by the key 'world'
. So for example with this:
print(myDictionary['hello'])
you will see that it prints out 2
, which is the value of the entry referred to by the 'hello'
key. Just like with a real-life dictionary, you look up items by their key.
To see this in action, you might add a print
to your code, like this:
class TagCloud:
def __init__(self):
self.tags = {}
def add(self, tag):
self.tags[tag.lower()] = self.tags.get(tag.lower(), 0) + 1
print(self.tags)
myTagCloud = TagCloud()
myTagCloud.add('Hello')
myTagCloud.add('World')
myTagCloud.add('Hello')
The result of this code is:
{'hello': 1}
{'hello': 1, 'world': 1}
{'hello': 2, 'world': 1}