This is the line that makes me all the trouble, My question is how can I remove one int(number) from books_library?
example of my book_library:
{'Books':
[{"Book's ID": {'003'},
"Book's Name": {'Avengers'},
"Book's Authors": {'Stan Lee, Jack Kirby'},
"Book's Published year": {'1939'},
"Book's Type": {'1'},
"Book's Copies": {15}}
books_library["Books"][book]["Book's Copies"][0] = books_library["Books"][book]["Book's Copies"][0] - 1
Returns me an Error : TypeError: 'set' object is not subscriptable
with open('loans_data.pkl', 'wb') as loans_save:
for book in range(len(books_library["Books"])):
if book_name_input in books_library["Books"][book]["Book's Name"]:
books_library["Books"][book]["Book's Copies"][0] = books_library["Books"][book]["Book's Copies"][0] - 1
book_details = {"ID":books_library["Books"][book]["Book's ID"],
"Name":books_library["Books"][book]["Book's Name"],
"Author":books_library["Books"][book]["Book's Author"]}
for customer in range(len(customers_library["Customers"])):
if customer_name_input in customers_library["Customers"][customer]["Customer's Name"]:
customer_details = {"Name": customers_library["Customers"][customer]["Customer's Name"],
"ID": customers_library["Customers"][customer]["Customer's ID"]}
loan_library["Customer"].update({customer_details:{book_details}})
pickle.dump(loan_library, loans_save)
CodePudding user response:
Due to documentation set
data structure is unordered collections of unique elements and that doesn't support operations like indexing or slicing etc.
>>> test_set = {1, 2, 3}
>>> test_set[0]
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'set' object is not subscriptable
In your case books_library["Books"][book]["Book's Copies"]
is set, so you should change it to list
or another type that you want (looks like it should be just integer).
CodePudding user response:
An important thing to learn is to pay attention to what exactly those errors say. They are intended to be helpful. Here, for example, it says
TypeError: 'set' object is not subscriptable
So what does subscriptable mean? Simplified, to get an item from a sequence or dictionary, or a user defined object by using a key or index. This is taken straight from the python docs. See here. But it says set is not subscriptable. So you go and look up what exactly a set is in the docs, and there you find out that its a builtin data structure that does not support subscription. And you see that the syntax for creating a set is {itemlist}. So you have just used sets for all the values in you dictionary, with unintended side effects! The solution is to not to use sets - storing different kinds of data in a dict works exactly as it would normally: {key: 1} stores and int(1), {key: [1,2]} a list and so on, so in your example you would use
"Book's Copies": 15
Conclusion: Listen to what python tries to tell you and use the docs, they are excellent.