Sorting a list on frequency of words: frequency not outputted when sorted

48 Views Asked by At

Im trying to write a program that will output the occurrence of words starting with each letter of the alphabet. So far I have gotten the code to work and output the right numbers. However the issue is when trying to sort the frequency alphabetically, the frequency isn't outputted too. I'm fairly new to python and I am unsure how to fix this.

My code looks like this:

f = open('textfile.txt','r')
data=f.read()
words= data.split()
#Alphabet occurence
alpha ={}
for alphaword in words:
  key = alphaword[0].upper()
  if key in alpha:
    alpha[key] +=1
  else:
    alpha[key] = 1
sortedalpha=sorted(alpha)
print("The occurence of words beginning with each letter is: ")
print(alpha)
print("")
print(sortedalpha)

This is the output without sorting (alpha)

{'T': 14, 'S': 4, 'W': 4, 'F': 1, 'R': 2, 'O': 7, 'A': 2, 'L': 2, 'G': 1, 'C': 1, 'D': 2, 'H': 1, 'M': 1, 'P': 2}

And this is the output when I try to sort it (sortedalpha)

['A', 'C', 'D', 'F', 'G', 'H', 'L', 'M', 'O', 'P', 'R', 'S', 'T', 'W']

However what I wanted was this

['A': 2, 'C': 1, 'D': 2,'F': 1,'G': 1, 'H': 1, 'L': 2, 'M': 1, 'O': 7, 'P': 2, 'R': 2, 'S': 4, 'T': 14, 'W': 4]

1

There are 1 best solutions below

1
Epic-legend128 On

So when you are calling sort() on a dictionary python only sorts the keys of the dictionary just how it is happening in your code. If you want to sort the whole dictionary based on the keys but also keeping their respective values then you would need to replace sortedalpha = sorted(alpha) with sortedalpha = dict(sorted(alpha.items())) just how Michael Butcher mentioned in one of your comments. This works because the .items() returns a read-only iterable of the whole dictionary which allows you to access both the keys and the values. So your code should look something like this:

f = open('textfile.txt','r')
data=f.read()
words= data.split()
#Alphabet occurence
alpha ={}
for alphaword in words:
  key = alphaword[0].upper()
  if key in alpha:
    alpha[key] +=1
  else:
    alpha[key] = 1
sortedalpha=dict(sorted(alpha.items())) # here is the change
print("The occurence of words beginning with each letter is: ")
print(alpha)
print("")
print(sortedalpha)

If you ever want to access a list of all the values of a dictionary without their respective keys then you can use .values() and for the keys you can use .keys().