python - What is this dictionary assignment doing? -


i learning python , trying use perform sentiment analysis. following online tutorial link: http://www.alex-hanna.com/tworkshops/lesson-6-basic-sentiment-analysis/. have taken piece of code mapper class, excerpt of looks this:

sentimentdict = {     'positive': {},     'negative': {} }  def loadsentiment():     open('sentiment/positive_words.txt', 'r') f:         line in f:             sentimentdict['positive'][line.strip()] = 1      open('sentiment/negative_words.txt', 'r') f:         line in f:             sentimentdict['negative'][line.strip()] = 1 

here, can see new dictionary created 2 keys, positive , negative, no values.

following this, 2 text files opened , each line stripped , mapped dictionary.

however, = 1 part for? why required (and if isn't how removed?)

the loop creates nested dictionary, , sets values 1, presumably use keys way weed out duplicate values.

you use sets instead , avoid = 1 value:

sentimentdict = {}  def loadsentiment():     open('sentiment/positive_words.txt', 'r') f:         sentimentdict['positive'] = {line.strip() line in f}      open('sentiment/negative_words.txt', 'r') f:         sentimentdict['negative'] = {line.strip() line in f} 

note don't need create initial dictionaries; can create whole set 1 statement, set comprehension.

if other code does rely on dictionaries values being set 1 (perhaps update counts @ later stage), it'd more performant use dict.fromkeys() class method instead:

sentimentdict = {}  def loadsentiment():     open('sentiment/positive_words.txt', 'r') f:         sentimentdict['positive'] = dict.fromkeys((line.strip() line in f), 1)      open('sentiment/negative_words.txt', 'r') f:         sentimentdict['negative'] = dict.fromkeys((line.strip() line in f), 1) 

looking @ source blog article shows dictionaries used membership testing against keys, using sets here better , transparent rest of code boot.


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -