gpt4 book ai didi

python - 不返回字典的正确值

转载 作者:太空宇宙 更新时间:2023-11-04 02:51:48 25 4
gpt4 key购买 nike

我对字典很陌生,我对这段代码有疑问。我不明白为什么它总是输出值 0。就像我输入的任何内容都进入了其他内容一样。它应该显示 0 的唯一原因是列表中缺少单词

if item in resultat.keys():
print(item, ": {}".format(resultat[item]))
else:
print(item, ": 0")

我正在使用的字典示例是从 txt 文件导入的:

pommes : 54
bananes
oranges : 30

输入示例

item.py data1.txt pommes

我得到的错误输出示例:

pommes : 0

预期输出

pommes : 54

这是我正在处理的代码。

import sys

def ligne(texte, item):
try:
with open(texte) as ouvrir:
mots_dict = {}
lecture = ouvrir.readlines()
for line in lecture:
line = line.strip('\n')
try:
mot, nombre = line.split(':')[1], int(line.split(':')[2])
except IndexError:
continue
if mot not in mots_dict.keys():
mots_dict[mot] = nombre
elif mot == item:
raise Exception('La ligne {} est un doublon.'.format(line))
return mots_dict
except IOError:
print("Le fichier", texte, "n'existe pas.")
sys.exit()

最佳答案

尝试拆分

' : ' 

不是

':'

因为如果你只用':'分割你的代码仍然会在单词之后和数字之前保留空格

关于python - 不返回字典的正确值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43636555/

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