[Python] How to sort a dictionary of word counts by value while preserving the original key...

Discussão em 'Python' iniciado por Stack, Novembro 23, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to count word frequencies in a text and then sort them in descending order of frequency. So if two words have the same frequency, they should remain in the same order they first appeared in the original text (not alphabetical order). See the example below to understand:

    Example input:

    Hi I live in America I love cooking


    After converting to lowercase, the expected output is:

    {"i": 2, "hi": 1, "live": 1, "in": 1, "america": 1, "love": 1, "cooking": 1}


    Current Approach:

    words = input().lower().split()
    d = {i: words.count(i) for i in words}
    dk = list(d.keys())
    dv = sorted(d.values())[::-1]
    sd = sorted(d.items())

    nd = dict()
    for i in dv:
    for j in dk:
    if d[j] == i:
    nd[j] = i
    print(nd)


    This works, but calling words.count() for every element makes the time complexity very poor, and the nested loops make it worse. I’m unable to figure out a better algorithm to replace this.

    Continue reading...

Compartilhe esta Página