实现字典反向功能的数据结构,这是使用Python的一个公共值的多个键映射。如果我正在解析一个例句 - "该计划很好并且执行得很好",所以我想要一组单词{" good"," well"映射到单个实体{" possitivity"}。使用Python
答案 0 :(得分:0)
为了避免重复,您可以按照注释中的建议初始化带有元组的主字典,然后在使用它之前将其“反转”到另一个字典中。如下:
wordpower = {
"positive": ("best" , "up" , "awesome" , "fantastic" , "happy" , "better" , "wonderful" , "good" ),
"negative": ("worst" , "down" , "terrible" , "horrible" , "sad" , "worse" , "dreadful" , "bad" )
}
reverse = {}
for k, v in wordpower.iteritems():
for word in v:
reverse[word] = k
pprint(reverse)
这将打印以下内容:
{'awesome': 'positive',
'bad': 'negative',
'best': 'positive',
'better': 'positive',
'down': 'negative',
'dreadful': 'negative',
'fantastic': 'positive',
'good': 'positive',
'happy': 'positive',
'horrible': 'negative',
'sad': 'negative',
'terrible': 'negative',
'up': 'positive',
'wonderful': 'positive',
'worse': 'negative',
'worst': 'negative'}