How to create an instance variable from the below list which contains a dictionary key called price and i am trying to retrieve the price list of all the books using a class called Library
1 ) Here is the list of books and their details
data = { "books" : [ { "number_of_pages" : 849,
"price" : 13.550000000000001,
"publish_date" : 2011,
"subjects" : [ "Time travel",
"Assassination"
],
"title" : "11/22/63"
},
{ "number_of_pages" : 732,
"price" : 7.9900000000000002,
"publish_date" : 1999,
"subjects" : [ "Authors",
"Custody of children",
"Grandfathers",
"Haunted houses",
"Novelists",
"Trials (Custody of children)",
"Widowers",
"Widows",
"Writer's block"
],
"title" : "Bag of bones"
},]}
2 ) I created a class called Library which will unpack the list and store the variables
class Library:
def __init__(self,**kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
#print(k,v)
if 'price' in v[0:][1]:
for c in v[0:][1].items():
if 'price' in c:
self.price=c['price']
def price_book(self):
return self.price
def __float__(self):
return self.price
Libra = Library(**data)
Price=Libra.price_book()
print(Price)
While trying to return using the instances its retuning the error for setting the variable for price ?
How to set the instance variable and retrieve list of prices in library ?
Regards
Update 1:
self.price=c['price']
TypeError: tuple indices must be integers or slices, not str
Update 2 :
class Library:
def __init__(self,**kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
self.price = []
for k, v in kwargs.items():
for i in range(len(v)):
self.price.append(v[i]['price'])
def price_book(self):
return self.price
def discount_book(self):
self.price=self.price
return list(map((lambda x: x -2), self.price))
def __float__(self):
return self.price
Libra = Library(**data)
Price=Libra.price_book()
Pri=Libra.discount_book()
print(Price)
print(Pri)
if 'price' in v[0:][1]:
for c in v[0:][1].items():
if 'price' in c:
self.price=c['price']
The items()
method of a dictionary returns key-value pairs as tuples.
Therefore c
is a tuple such as ('price', 7.99)
.
Tuples are indexed by integers, not strings.
You probably want self.price = c[1]
instead.
Just having trouble seeing where you are hung up, if it's retrieving the prices or setting them to the instance.
def __init__(self, **kwargs):
for k, v in kwarg.items():
setattr(self, k, v)
self.price = []
for k, v in kwargs.items():
for i in range(len(v)):
self.price.append(v[i]['price'])
(xenial)vash@localhost:~/python/AtBS$ python3.7 comphren.py [13.55, 7.99]
Suggestion by Request
One thing I would I didn't do because I'm unsure I think the use of data
creates unneeded nesting that unless you are going to have books
and say movies
otherwise you could just call this whole thing books
and remove one level of nesting. Also this method logs duplicates, which I worked around using set
but you could avoid appending duplicates with more code, didn't want to do too much because still unsure of entire task.
But if the goal was just to create these lists of each piece of data this code will work:
pages = []
publish_dates = []
subjects = []
titles = []
prices = []
for v in data.values():
for i in range(len(v)):
for w, x in v[i].items():
pages.append(v[i]['number_of_pages'])
publish_dates.append(v[i]['publish_date'])
titles.append(v[i]['title'])
prices.append(v[i]['price'])
for a in v[i]['subjects']:
subjects.append(a)
print(f"Pages: {set(pages)}\nPublish Dates: {set(publish_dates)}\n" \
f"Subjects: {set(subjects)}\nTitles:{set(titles)}\n" \
f"Prices: {set(prices)}")
Output
(xenial)vash@localhost:~/python/AtBS$ python3.7 comphren.py Pages: {849, 732} Publish Dates: {2011, 1999} Subjects: {'Time travel', 'Widows', 'Authors', 'Widowers', 'Assassination', 'Haunted houses', 'Grandfathers', "Writer's block", 'Novelists', 'Trials (Custody of children)', 'Custody of children'} Titles:{'11/22/63', 'Bag of bones'} Prices: {13.55, 7.99}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.