python - if-else comprehension with dictionary not working in python3 -


dlist=['all loving','all bros','and sis'] 

i create dictionary such words (as keys) assigned value index of dlist in words appear. example, 'all':{0,1}, 'my':{0,1},'sis'={2} etc.

somehow not work:

dict={} {w:{num} if w not in dict.keys() else dict[w].add(num) (num,strn) in enumerate(dlist) w in strn.split()} 

this returns

{'all':{2}, 'my':{2}} 

looks else statement being ignored. pointers? thanks

this doesn't work because trying access dict.keys while creating dict in dict comprehension. if in loop, dict.keys updated each element, dict comprehensions ensures dict not updated mid-creation improve speed.

something should work:

mydict = {} (num, strn) in enumerate(dlist):     w in strn.split():         if w not in mydict:             mydict[w] = {num}         else:             mydict[w].add(num) 

Comments

Popular posts from this blog

libGdx unable to find files in android application data directory -

php - Webix Data Loading from Laravel Link -

python - Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] error -