So, I'm writing a function that reads lines from a file and makes a list, which is then passed through loops to create a dictionary that keeps each line as a key and then increments the key value. Basically, my only issue is the way it is printing out is not as I intended. Code here:
import re
import string
def readInputFile():
print("Reading \"GroceryList.txt\"")
f = open("GroceryList.txt")
itemList = f.readlines()
f.close()
itemDict = { }
for ln in itemList:
i = 0
itemCount = 0
while i < len(itemList):
if ln == itemList[i]:
itemCount += 1
itemList.pop(i)
itemDict[ln] = itemCount
i += 1
for key in itemDict:
print("{}: {}".format(key, itemDict[key]))
For whatever reason, it's printing like this:
Spinach
: 5
Broccoli
: 1
... etc.
whereas my intention was for it to be:
Spinach: 5
Broccoli: 1
... etc.
The dictionary is setting itself as intended, with correct keys and key values, it's just printing in this way and I'm not sure why? I'm still a rookie so I'm not exactly sure how to correct this.