Reputation: 129
i am pretty new to dictionaries and i have a problem with this code. I don't understand why its always outpuing the value 0. it's like if anything i enter goes into this else. The only reason it should display 0 is if the word is missing from the list
if item in resultat.keys():
print(item, ": {}".format(resultat[item]))
else:
print(item, ": 0")
Exemple of the dictionnary i am using that is imported from a txt file:
pommes : 54
bananes
oranges : 30
Exemple of input
item.py data1.txt pommes
Exemple of erroneous output i am getting:
pommes : 0
exptected output
pommes : 54
This is my code im working on.
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()
Upvotes: 2
Views: 418
Reputation: 74
Try to split with
' : '
not
':'
Because if you split just with ':' your code will still keep the space after the word and before the number
Upvotes: 2