Christopher Lux
Christopher Lux

Reputation: 21

Append elements of list to dict

I have a random text file and want to put all its words into a dict, because I have to count them.

raw_data = open("ipsum.txt", "r").readlines()

data = []
word_dict = {

    'word' : 0

}

for lines in raw_data:

   lines = lines.strip('\n')
   data.append(lines.split(" "))


print(data)

for word in data:
    if word not in word_dict:
        word_dict[word] = 0

But I always get the following error message:

  if word not in word_dict:
TypeError: unhashable type: 'list'

I don't know how to continue.

Upvotes: 1

Views: 54

Answers (1)

pissall
pissall

Reputation: 7399

A much easier and cleaner solution would be the following:

file = open("ipsum.txt", "r")
wordcount={}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
for k,v in wordcount.items():
    print k,v

And a more pythonic way would be:

from collections import Counter
file = open("ipsum.txt", "r")
wordcount = Counter(file.read().split())

You can sort them as well by using

wordcount = sorted(wordcount.items(), key=lambda x:x[1], reverse=true)

Upvotes: 2

Related Questions