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

Load Balancing in Bluemix using custom domain and DNS SRV records -

oracle - pls-00402 alias required in select list of cursor to avoid duplicate column names -

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