python - Why is my dictionary duplicating a key but not the value? -
python - Why is my dictionary duplicating a key but not the value? -
i'm starting tinker in python, , i've been doing (super easy) challenges /r/dailyprogrammer. started working on #186 easy this input, , right @ point of counting pieces of candy. code far:
myinput = open("c:/users/jacob/desktop/python/186/candy.txt").readlines() candydict = dict() line in myinput: if line not in candydict: candydict[line] = 0 if line in candydict: candydict[line] += 1 item in candydict.keys(): print(str(candydict[item]) + " : " + item.replace('\n', "")) and output:
44 : skittles 62 : stone 45 : jolly rancher 41 : snickers 41 : runts 36 : almond joy 39 : candy corn 46 : popcorn 48 : peppermint candy 50 : tootsie roll 41 : nerds 44 : bubblegum 46 : lollipop 46 : sweetness tarts 47 : m&ms 50 : crunch bar 67 : kit kat 53 : lifesavers 48 : tangy taffy 57 : peanut butter cup 48 : smarties 1 : m&ms why there m&ms appended end of file? think because m&ms lastly line of file, doesn't explain me why duplicate that. clue why much appreciated.
lines have line ending character ("\n") @ end of them, noticed when replaced them printing. lastly line in file not (it may or may not, description give seems doesn't).
the string "m&ms\n" not same string "m&ms".
it's possible 1 of strings has space @ end.
at start of loop, strip off spaces , newlines with:
for line in myinput: line = line.strip() # etc python
Comments
Post a Comment