-1

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

Sociopath
  • 13,068
  • 19
  • 47
  • 75
Charlotte
  • 55
  • 1
  • 2
  • 7

2 Answers2

0

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(" ")}

  • wonderful one liner I love it , but "(btw, I cant use too many "shortcuts", since it's a task that I've been given.)" was a condition of OP question – vash_the_stampede Sep 16 '18 at 15:46
  • Code only answers are generally discouraged on Stack Overflow as they can be confusing for beginners. Please consider adding a small paragraph explaining what you are doing and how it works. – Shadow Sep 17 '18 at 01:17
0
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}
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20