Reputation: 453
So, I have an assignment and I need to build an administration for the borrowed books. I have a list of books(100 books) in a listofbooks.json. From listofbooks.json, I can add books to the other jsonfile named Borrowedbooks.json, but the problem is I can't "unloan" the book. So what I try to do to "unloan" a book is:
import json
def DeleteBook(p):
for x in B:
if x['title'] == C[p]['title']:
del B[p]
with open('Borrowedbooks.json','w') as output:
json.dump(B,output,indent=2)
print("Deleted succesfully!")
break
else:
print("The book that you want to delete doesn't exist")
break
C = json.load(open('ListOfBooks.json'))
B = json.load(open('Borrowedbooks.json'))
The problem with this code is that if someone loans a book with ID 2 and ID 4, it is checking the indexes but what I want is that it checks the ID of the book but that's the point what I can't do. The index is incorrect at the borrowbooks.jsonfile and it is going to the else statement. So on my ListOfBooks.jsonfile, the book with ID 2 is on index 2, but in borrowedbooks.json the book with ID 2 is on index 0 The borrowedbooks.json looks like this:
[
{
"ID": 2,
"author": "Dante Alighieri",
"country": "Italy",
"imageLink": "images/the-divine-comedy.jpg",
"language": "Italian",
"link": "https://en.wikipedia.org/wiki/Divine_Comedy\n",
"pages": 928,
"title": "The Divine Comedy",
"year": 1315
},
{
"ID": 3,
"author": "Unknown",
"country": "Sumer and Akkadian Empire",
"imageLink": "images/the-epic-of-gilgamesh.jpg",
"language": "Akkadian",
"link": "https://en.wikipedia.org/wiki/Epic_of_Gilgamesh\n",
"pages": 160,
"title": "The Epic Of Gilgamesh",
"year": -1700
}
]
My question is how can I make a function where the user writes the book ID and it will delete the dictionary inside the borrowedbooks.json.
Upvotes: 0
Views: 55
Reputation: 46
So from what I am understanding is that when you input 2 into a returned book ID variable or array, you can only get index of 2 instead of ID of 2.
What you can do is use bookID = json.get('ID')
and a function to check similar to what you did up there. You are using arrays so keep that in mind.
Upvotes: 1