pythondictionarycountcharacterletters

How can I count letters per word in a string using dictionary? (Python)


So, I've found methods for counting the amount of words in a string and counting the amount of letters all together, but I have yet not found out how I can count the amount of letters per word in a string. Saying that the string would be f.

E.x

"I like cake"

I would like a result somewhat like this:

{"I":1, "like":4, "cake":4}

Probably not too hard, but I'm fairly new to coding, so I could use some help:) (btw, I cant use too many "shortcuts", since it's a task that I've been given.)


Solution

  • count = {}
    
    example = "I like cake"
    
    for i in example.split():
        count[i] = len(i)
    
    print(count)
    

    Output :

    (xenial)vash@localhost:~/python/stack_overflow$ python3.7 letters_dict.py 
    {'I': 1, 'like': 4, 'cake': 4}