goldenasian
goldenasian

Reputation: 274

Add Key and value to dictionary by using class method

So what I want to do is add up new pair of key& value to empty dictionary. by using Class method call"learn"

 print(madlib.vocabulary)
here is what I got from code:

    {'name': {'mercator', 'caesar'}, 'thing': {'maps', 'coordinates'}, 'citizens': {'martians', 'germans', 'belgians'}, 'discipline': {'colonisation'}}


additional explain about method:

A method learn that can be used to add one or more words from a certain category to the object's vocabulary. The method takes two arguments: i) the category of the new words and ii) one or more words from this category. In case a single word is passed as the second argument, the word may be passed as a string. In case multiple words are passed as the second argument, the words must be passed as a list, a tuple or a set. The method must make sure that the dictionary referenced by the vocabulary property is extended by adding the words to the set onto which the given category is mapped by the dictionary. In case the dictionary did not have a key corresponding to the given category, a new key-value pair must be added to it, with the key corresponding to the given category and the value being a set containing the given words. All categories and words included in the dictionary must always be converted into lowercase.

Upvotes: 1

Views: 104

Answers (1)

deadshot
deadshot

Reputation: 9061

You need to update self.vocabulary[category] = set(aa) statement as below. The problem in your code each time you are assigning a new set instead of updating.

if category in self.vocabulary:
  self.vocabulary[category].update(set(aa))
else:
  self.vocabulary[category] = set(aa)

Upvotes: 3

Related Questions