I am trying to compare each item in a the list "lines" to the dictionary "dic", and then add the item from lines to dic if it doesn't exist, or add 1 to the value of the key in the dictionary.
import string
def uniques():
file = open("test.txt", "r")
dic = {}
data = file.read().replace('\n', ' ')
strip = removePunctuation(data)
lines = strip.split(' ')
print(strip)
print(lines)
for item in lines:
#this produces an error of unhashable type: 'list'
if lines in dic:
dic[item] = dic[item] + 1
else:
print("else ran")
dic[item] = 1
for item in dic:
print(item, dic[item])
print("There are " + str(len(dic)) + " items in the dictionary")
def removePunctuation(text):
text = text.strip()
return text.rstrip(string.punctuation)
uniques()
its
if item in dic:
dic[item] = dic[item] + 1
instead of
if lines in dic:
dic[item] = dic[item] + 1
if item in dic.values():
instead of if lines in dic:
This would create a dict_value list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.