-1

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.

Syd
  • 3
  • 2

1 Answers1

0

You're reading each line from the file - this will still have the newlines at the end of values. You can remove whitespace and new lines by calling .strip() on the string:

itemDict[ln.strip()] = itemCount

If the goal is to count the number of times the ingredients appear in the shopping list, you can use the built-in Counter class under collections instead.

from collections import Counter

...

item_count = Counter(itemList)
#  item_count will now be a dictionary-like object with the 
#  line as the key and the number of occurrences as the value.

To strip the newline from each list in your file, you can apply strip to every value in the itemList:

item_count = Counter(map(lambda s: s.strip(), itemList))

You can then print out the item_count counter in the same manner as you already do.

MatsLindh
  • 49,529
  • 4
  • 53
  • 84
  • Wow, this is my first time posting a question, you guys are quick lol! The .strip() function solved everything. Unfortunately I'm only working with what my school teaches me at the moment so I wasn't familiar with the Counter class or the syntax with map(lambda s: ...etc) and whatnot, but regardless I've got it figured out now with .strip(). Much appreciated! – Syd Jun 17 '22 at 23:06