Python: txt into dictionary. Split() TypeError: unhashable type: 'list' -
i started python , i'm having troubles 1 exercise. sorry if question "basic stuff" i've done research on google , can't find short , not complicated answer. , exercise:
"write program reads words in words.txt , stores them keys in dictionary. doesn't matter values are. can use in operator fast way check whether string in dictionary."
i tried this:
import os os.chdir("/users/missogra/documents") fname = input("file name: ") if len(fname) < 1 : fname = "words.txt" fh= open(fname) counter = 0 dictionairy = dict() line in fh: word = line.rstrip() dictionairy[word] = counter counter += 1 print(dictionairy)
however, don't words, sentences. thought use split()
this:
import os os.chdir("/users/missogra/documents") fname = input("file name: ") if len(fname) < 1 : fname = "words.txt" fh= open(fname) counter = 0 dictionairy = dict() line in fh: word = line.rstrip().split() dictionairy[word] = counter counter += 1 print(dictionairy)
but doesn't work. get:
dictionairy[word] = counter typeerror: unhashable type: 'list'
can please explain me why happening , give me hint how can fix it? please, pretty please?
if don't care values using wrong container, use set
not dict:
st = set() line in fh: word = line.split() st.update(word)
calling rstrip redundant if splitting simple line.split()
, call set.update
need.
Comments
Post a Comment