We need to make two dictionaries, one for prices and another for quantities from the same text file called Initial_inventory-1.txt. Both dictionaries will have the product name as the key in the dictionary.
My output gives a dictionary with the names, prices, and then the first letter of the name and I don't know why. It happens for both dictionaries.
def read_file(file_name, prices, quantities):
file = open(file_name, 'r')
for line in file:
product = line.strip('\n').split(';')
name, price = product[0], product[1]
prices[name] = price
for price in product[0]:
prices.setdefault(price, []).append(name)
name, quantity = product[0], product[2]
quantities[name] = quantity
for quantity in product[0]:
quantities.setdefault(quantity, []).append(name)
print(prices)
print(quantities)
main function:
def main():
#init dictionaries
prices = {}
quantities = {}
#read_file
read_file("initial_inventory-1.txt", prices, quantities)
main()
There is more to the assignment, which is why they are in those functions, I CANNOT get rid of them. Thank you in advance!
CodePudding user response:
product[0] is the product name, which is a string. When you iterate over that, you're iterating over the characters in the name.
The keys of the prices and quantities dictionaries should be the name. You should use that as the first argument to setdefault(). You shouldn't assign to the dictionary first, that's replacing the list of prices and quantities with this price and quantity.
def read_file(file_name, prices, quantities):
file = open(file_name, 'r')
for line in file:
name, price, quantity = line.strip('\n').split(';')
prices.setdefault(name, []).append(price)
quantities.setdefault(name, []).append(quantity)
print(prices)
print(quantities)
