0

I am new to coding and I am starting with python. I am trying to sort dictinary by the occurrence of the word. here is the code i am using

lis = ['Now when I am faced with a new situation I am not so nervous.'] 
for word in lis:

      word = word.strip()
      word = word.lower()
      each = word.split(" ")

for p in each:
      lis.append(p)

d = {}


for p in lis:
    if p in d:
        d[p] = d[p] + 1
    else:
        d[p] = 1

for c in sorted(d):
    print(c, d[c])

here is the result, i am getting alphabetically

a 1
am 2
faced 1
i 2
nervous. 1
new 1
not 1
now 1
situation 1
so 1
when 1
with 1

and here is the result I am trying to get. ordered or sorted by the frequency of the word. as you can see start with the biggest number which in this case 2.

i 2
am 2
now 1
when 1
faced 1
with 1
a 1
new 1
situation 1
not 1
so 1
nervous 1
macropod
  • 12,757
  • 2
  • 9
  • 21
moe
  • 1
  • 1

1 Answers1

0

You can use collections.Counter and its method most_common:

from collections import Counter

lis = ['Now when I am faced with a new situation I am not so nervous.']

counter = Counter(word.strip('.').lower() for word in lis[0].split())

for word, c in counter.most_common():
    print(f"{word} {c}")

# i 2
# am 2
# now 1
# when 1
# faced 1
# with 1
# a 1
# new 1
# situation 1
# not 1
# so 1
# nervous 1

If you want to implement it manually, you can use sorted with key parameter:

for word, c in sorted(counter.items(), key=lambda x: x[1], reverse=True):
    print(f"{word} {c}")

Note that this also applies to your manually constructed dict d.

j1-lee
  • 13,764
  • 3
  • 14
  • 26