1

I am working on this code to print all the letters that follow a vowel in words of string and count the frequency using regex in python

import re
string = 'In 1996, the Council Higher Education approved the creation of the Center Consulting Research which was renamed King Abdullah Center Consulting Research. '
result = re.findall(r'[aeiou][^aeiou\s]+', string)
myArr = {}
for value in result:
  if not value[1] in myArr:
    myArr[value[1]] = 0
  myArr[value[1]] += 1
 
print(myArr)
for chr, value in myArr.items():
    print(chr, "->", value)

the output:

n -> 11
l -> 4
g -> 1
r -> 5
c -> 2
t -> 2
p -> 1
v -> 1
d -> 2
f -> 1
s -> 3
m -> 1
h -> 1

it's work good but I need to print it in Descending Order according to their occurrence frequency. In fact, I don't have enough experience in python I try sorted(myArr, key=lambda myArr: value[1]) but it doesn't work. Is there any way to sort?

Expected Output:

n -> 11
r -> 5
l -> 4
s -> 3 
....
fyafee
  • 53
  • 7
  • Check out this answer https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value – chase Mar 22 '22 at 16:00
  • You can use "items()" method on dict to create an iterator of tuples which you can feed into "sorted". The lambda function for the key then just needs a minor adjustment. – Michael Butscher Mar 22 '22 at 16:01
  • Also a hint, if you need to put a type name in a variable (which is generally not great practice), make darn sure it's the right type. You have a variable called `myArr` that's a *dictionary*. – Nick Bailey Mar 22 '22 at 16:05
  • Calling a dictionary `myArr` is kind of misleading. – Matthias Mar 22 '22 at 16:08

1 Answers1

0

You can put the output of the array into a dict (or even better would be to directly create a dictionary) and do:

d = {'h':1,'a':3,'v':5,'t':2,'f':4} # d is the dictionary mentioned above
a = sorted(d.items(), key=lambda x: x[1])    
print(a)
teoML
  • 784
  • 4
  • 13