Python 使用类方法向字典添加键和值

Python 使用类方法向字典添加键和值,python,class,dictionary,Python,Class,Dictionary,所以我要做的是将新的一对键和值添加到空字典中。通过使用类方法调用“learn” 您需要更新如下的self.词汇表[category]=set(aa)语句。每次分配新集合而不是更新时,代码中的问题都会出现 if self.词汇表中的类别: self.词汇表[category].更新(set(aa)) 其他: self.词汇表[类别]=set(aa) 您需要更新如下self.词汇表[category]=set(aa)语句。每次分配新集合而不是更新时,代码中的问题都会出现 if self.词汇表中的类

所以我要做的是将新的一对键和值添加到空字典中。通过使用类方法调用“learn”


您需要更新如下的
self.词汇表[category]=set(aa)
语句。每次分配新集合而不是更新时,代码中的问题都会出现

if self.词汇表中的类别:
self.词汇表[category].更新(set(aa))
其他:
self.词汇表[类别]=set(aa)

您需要更新如下
self.词汇表[category]=set(aa)
语句。每次分配新集合而不是更新时,代码中的问题都会出现

if self.词汇表中的类别:
self.词汇表[category].更新(set(aa))
其他:
self.词汇表[类别]=set(aa)

为什么不按原样存储单词呢。你对这些词做了什么?@komatiraju032我刚刚添加了关于方法的额外解释,每个词都有不同的类型,并且应该遵循其关键字的大小写,所以。。。。这就是我想要的答案为什么不按原样存储单词呢。你对这些词做了什么?@komatiraju032我刚刚添加了关于方法的额外解释,每个词都有不同的类型,并且应该遵循其关键字的大小写,所以。。。。这就是我想要的检查答案谢谢我错过了那个条件!谢谢你,我错过了那个条件!
 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.