如何使用字典计算字符串中每个单词的字母数? (Python)

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

所以,我找到了计算字符串中单词数量和计算所有字母数量的方法,但我还没有找到如何计算字符串中每个单词的字母数量.说字符串是 f.

E.x

"I like cake"

我想要这样的结果:

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

可能不太难,但我对编码还很陌生,所以我需要一些帮助:)(顺便说一句,我不能用太多 "shortcuts",因为这是我一直在做的任务给出。)

这可以使用字典理解来完成,我们可以使用简单的表达式创建字典。 字典推导式采用 {key: value for (key, value) in iterable}

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

count = {}

example = "I like cake"

for i in example.split():
    count[i] = len(i)

print(count)

输出:

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