[Python] How to count the number of words of each length in a list using dictionary...

Discussão em 'Python' iniciado por Stack, Março 7, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to find the occurrences of all the words in a list using dictionary comprehension, using the length of the word as the key, and then the occurrence count of words of each length as the value.

    def words_lengths_map(text):
    mod_text = ["hello", "this", "is", "a", "list", "of", "words"]
    dict1 = {len(k): k.count(k) for k in mod_text}
    print(dict1)


    This produces the correct key, but the value is always 1.

    This is the output I want:

    {5: 2, 4: 2, 2: 2, 1: 1}


    How can I get that?

    Continue reading...

Compartilhe esta Página