gpt4 book ai didi

python - 如何检查字母(值)是否在字典中?

转载 作者:行者123 更新时间:2023-12-04 14:49:21 26 4
gpt4 key购买 nike

希望你一切顺利。我正在研究字典程序:

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

我想弄清楚如何检查字母是否在字典中。如果不是,则显示消息“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']

如果您能告诉我哪里出了问题以及如何解决,我将不胜感激。

最佳答案

检查键,而不是值(因为值是数字,而不是字母)-

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相反

关于python - 如何检查字母(值)是否在字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69309232/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com