You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何检查字母是否在字典中及现有代码问题修复

Python字典频次统计代码问题及修复方案

存在的问题

  • 字母存在性判断逻辑错误:原代码判断newLetter in newDic.values(),但newDic的键为输入的字母,值为对应字母的出现频次,应该判断字母是否在字典的键中,直接用newLetter in newDic即可。
  • 引用未定义变量:原代码调用message.count(newLetter)获取频次,但代码中从未定义message变量,直接取newDic[newLetter]即可得到对应字母的频次。
  • 输出不符合要求:缺少约定的输出前缀(如Dictionary: 、Frequency count of that letter: 等),还存在拼写错误Dictinary,正确拼写为Dictionary。

修复后完整代码

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("Dictionary: ", newDic)

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

if newLetter in newDic:
  print("Frequency count of that letter:", newDic[newLetter])
  newDic.pop(newLetter)
  print("Dictionary after that letter removed:", newDic)
else:
  print("Letter not in dictionary")

sortedDic = sorted(newDic)
print("Letters sorted:", sortedDic)

效果说明

运行修复后的代码,输入Magee, Mississippi后选择字母s,输出结果与你给出的预期效果完全一致。

内容的提问来源于stack exchange,提问作者MBahreman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 21:45:04