0

I want to save dictionary in a CSV file.

Firstly, I got program and want to understand the following extract at the end of the program and what would the output look like in notepad. I am unable to run this code as it shows the following error

Traceback (most recent call last):
  File "d:\CSA~\Inventory-Management\ims.py", line 258, in <module>
    details.write(str(i+1)+"#"+str(unit_price[i+1])+"\n")
KeyError: 5

# Write the updated inventory to the file
details = open("stock.txt", "w")
no_items = len(unit_price)
details.write(str(no_items)+"\n")
for i in range(0, no_items):
    details.write(str(i+1)+"#"+str(unit_price[i+1])+"\n")

for i in range(0, no_items):
    details.write(str(i+1)+"#"+description[i+1]+"\n")

for i in range(0, no_items):
    details.write(str(i+1)+"#"+str(stock[i+1])+"\n")

details. Close()

And what to change to make this file work? like it works fine but then I use the "Q" option to exit it shows that above given error when it tries to write the date into the file

Python File: https://drive.google.com/file/d/1pS70u7-WDbti_0vPiD0nAAIG2sWCkA_e/view?usp=sharing

I want to understand that extract of code, and then further fix it to make it to write data to the file.

Thanks & Regards

  • `unit_price[i+1]` Appears to be reading past the end. Try `unit_price[i]`. Same for others. – 001 Nov 21 '22 at 13:52
  • I changed all the i+1 to i but still the error persists @JohnnyMopp, this time with KeyError: 0 if that's relevent – Animish Yadav Nov 21 '22 at 13:58
  • I guess these are dictionaries. [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/q/3294889) – 001 Nov 21 '22 at 14:10

0 Answers0