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

3.3k Views Asked by At

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.)

2

There are 2 best solutions below

0
vash_the_stampede On BEST ANSWER
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}
2
Basavaraju US On

This can be done using Dict comprehension, We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}

{word:len(word) for word in "I like you".split(" ")}