mk1138
mk1138

Reputation: 55

How to remove dictionary items with spaces as their values in Python?

I'm building a dictionary by assigning keys to be individual characters from a string, and values to be the frequency of those characters in the string. The intention is to count the most frequent letter in the string. As I'm trying to count only letters I would like to discard spaces from counting.

I wrote the following:

sentence = 'This is some sentence.'

dict_characters = dict.fromkeys(sentence, 0)

for character in sentence:
    dict_characters[c] += 1

dict_letters = {k:v for k,v in dict_characters.items() if v != ' '}

This last line is where I'm stuck. Items that have spaces for values are not removed from the dictionary as I can tell when I print the new dictionary:

>>> dict_letters:  {'T': 1, 'h': 1, 'i': 2, 's': 4, ' ': 3, 'o': 1, 'm': 1, 'e': 4, 'n': 2, 't
': 1, 'c': 1, '.': 1}

As you can see ' ': 3 is still in there. I would like it out but no matter how I try to exclude that space character in v != ' ' part of the syntax I cannot take it out. Any idea what I'm doing wrong?

Upvotes: 1

Views: 773

Answers (2)

In Hoc Signo
In Hoc Signo

Reputation: 495

You are using the wrong variable.

Replace

dict_letters = {k:v for k,v in dict_characters.items() if v != ' '}

with

dict_letters = {k:v for k,v in dict_characters.items() if k != ' '}

Note the replacement of v with k. v represents the value of the character; k is the character itself.

Upvotes: 3

Alireza HI
Alireza HI

Reputation: 1933

You are checking the v while there is a key that is ' '.

Try to change it to k or have both like below:

dict_letters = {k:v for k,v in dict_characters.items() if v != ' ' and k != ' '}

Upvotes: 0

Related Questions