如何检查字典中是否存在某个字母(值)?

3

希望你一切顺利。我正在开发一个词典程序:

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)

在此部分之前,一切都正常:

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")

我正在尝试找出如何检查字母是否存在于字典中。如果不存在,则显示“字典中没有该字母”的消息。否则,显示该字母的频率计数,将该字母从字典中删除,并在删除该字母后显示字典。

它应该看起来像这样:

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']

我会非常感激如果您能告诉我哪里出了问题以及如何修复它。

1
您正在检查它是否在值中而不是键中。您需要使用 if newLetter in newDic 而不是 if newLetter in newSic.values() - joshmeranda
这回答解决了您的问题吗?检查字典中是否存在给定键 - Joe
你是想检查该值在字典中是作为键、值还是两者都有吗?因为这些是不同的问题。 - BTables
1个回答

2
检查键而不是值(因为该值是一个数字,而不是一个字母)-
if newLetter in newDic:  # Or if newLetter in list(newDic.keys())
  print("Number of occurrence of", message.count(newLetter))

对于这个字典:{'M': 2, 'A': 1, 'G': 1, 'E': 2, 'I': 4, 'S': 4, 'P': 2},你可以使用Collections.Counter代替。


它确实起作用了。我删除了 .values()。谢谢,我会在 Collections.Counter 上进行研究。 - MBahreman
我刚刚检查了一下,“出现次数”也无法工作。你有什么想法可以修复它吗? - MBahreman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接