Home > Software design >  How do I get access to the numbers or score that i've given the words in my dictionary
How do I get access to the numbers or score that i've given the words in my dictionary

Time:10-31

This is the code:

word_count = {}

with open(file, "r") as fi:
    for line in fi:
        words = line.split()  

        for word in words:
            word = word.lower()

            if word not in word_count: 
                word_count[word] = 0 

            word_count[word]  = 1

    print(word_count)

Output:

{'thou': 2, 'ancient,': 1, 'free': 1}

I want to somehow get access to the numbers 2,1 and 1 so I can get the average usage of the words in my text file. So my question is how do I do it?

I've tried to use the dictionary somehow to add up the numbers in the dictionary but in it, I have both the words and the numbers so I get "TypeError: 'int' object is not iterable".

CodePudding user response:

You should use the dict.values() method. Like this:

word_freq = {'thou': 2, 'ancient,': 1, 'free': 1}

avg = sum(word_freq.values())/len(word_freq)
print(avg)

CodePudding user response:

I want to somehow get access to the numbers 2,1 and 1 so I can get the average usage of the words in my text file. So my question is how do I do it?

Well, there are many ways to do this, but I think the fastest way is this one:

total = sum(word_count.values())

Then to get the average simply use the / operator.

CodePudding user response:

You can also use loop with dicts if you want to change anything with the value.

sum_words = 0
for i in word_count.values():
    print(i)
    sum_words  = i
print("Avg: "   str(sum_words/len(word_count)))

CodePudding user response:

The most basic way to access values in a dictionary is by indexing it

thou_count = word_count['thou']

If you aren't sure if a key is in your dictionary and you want to try to access it you can use get and provide a default value

thee_count = word_count.get('thee', -1)

If you want to get all the values, you can use word_count.values() which returns a result you can iterate through. Oftentimes though you will want to convert the result to a list

print(list(word_count.values()))

Similarly, you can access keys with word_count.keys() or you can iterate through key-value pairs using

for key, value in word_count.items():
    print(f"{key=}, {value=}")
  • Related