MBahreman
MBahreman

Reputation: 55

How to check whether the letter (value) is in the dictionary?

I hope you are doing well. I'm working on a dictionary program:

strEntry = str(input("Enter a string: ").upper())
strEntry = strEntry.replace(",", "")
strEntry = strEntry.replace(" ", "")

print('')

def freq_finder(strFinder):
  dict = {}
  for i in strFinder:
    keys = dict.keys()
    if i in keys:
      dict[i] += 1
    else:
      dict[i] = 1
  return dict

newDic = freq_finder(strEntry)

print(newDic)

newLetter = str(input("Choose a letter: ").upper())

if newLetter in newDic.values():
  print("Number of occurrence of", message.count(newLetter))
  newDic.pop(newLetter)
  print("Dictinary after that letter removed:", newDic)
else:
  print("Letter not in dictionary")

sortedDic = sorted(newDic)
print(sortedDic)

Everything works fine before this part:

newLetter = str(input("Choose a letter: ").upper())

if newLetter in newDic.values():
  print("Number of occurrence of", message.count(newLetter))
  newDic.pop(newLetter)
  print("Dictinary after that letter removed:", newDic)
else:
  print("Letter not in dictionary")

I'm trying to figure out how to check whether the letter is in the dictionary. If it is not, display the message “Letter not in dictionary”. Otherwise, display the frequency count of that letter, remove the letter from the dictionary and display the dictionary after that letter has been removed.

It should look something like this:

Enter a string: Magee, Mississippi

Dictionary:  {'M': 2, 'A': 1, 'G': 1, 'E': 2, 'I': 4, 'S': 4, 'P': 2}
Choose a letter: s
Frequency count of that letter: 4
Dictionary after that letter removed:  {'M': 2, 'A': 1, 'G': 1, 'E': 2, 'I': 4, 'P': 2}
Letters sorted: ['A', 'E', 'G', 'I', 'M', 'P']

I would highly appreciate it if you could tell me what's wrong and how to fix it.

Upvotes: 3

Views: 639

Answers (1)

PCM
PCM

Reputation: 3011

Check for the keys, not the value (Because the Value is a number, not a letter) -

if newLetter in newDic:  # Or if newLetter in list(newDic.keys())
  print("Number of occurrence of", message.count(newLetter))

For this - Dictionary: {'M': 2, 'A': 1, 'G': 1, 'E': 2, 'I': 4, 'S': 4, 'P': 2}, you could use Collections.Counter instead

Upvotes: 2

Related Questions