Home > Enterprise >  How to make dictionary not count "blank" as keys?
How to make dictionary not count "blank" as keys?

Time:06-24

I have a code where I write a sentence, and then it makes a dictionary when the keys are the letters in the sentence and the values are the amount of times each letter appears in the sentence. The code counts spacebar as a letter, how can I prevent that?

sentence = input("write a sentence: ")

d=dict()
for n in sentence:
    if n in d:
        d[n] =1
    else:
        d[n]=1
print(d)

CodePudding user response:

Just check if the traversed character is " ":

sentence = input("write a sentence: ")

d=dict()
for n in sentence:
    if n != " ":
        if n in d:
            d[n] =1
        else:
            d[n]=1
print(d)

CodePudding user response:

You just need to test each character value for ' '. If it's a space, ignore it. You could also replace all spaces before parsing the sentence.

Using Counter is the best solution but here are two options without Counter:

sentence = input("write a sentence: ")

d = dict()

for n in sentence.replace(' ', ''):
    d[n] = d.get(n, 0)   1

print(d)

...or...

sentence = input("write a sentence: ")

d = dict()

for n in sentence:
    if n != ' ':
        d[n] = d.get(n, 0)   1

print(d)
  • Related