Reputation: 11
I have created the following dictionary:
Book_list={
'Fiction': {1001: ['Pride and Prejudice', 'available'],
1002: ['Fahrenheit 451', 'available']},
'Horror': {2001: ['House of leaves', 'available'],
2002: ['The Shinking', 'available']}}
now I want to store the status that is "available" in a variable with its key so that it can be used further for delete or update.
So the output I mean is like:
status={1001:available,1002:available,2001:available,2002:available}
Please help me by telling that how could I get this output.
Upvotes: 0
Views: 120
Reputation: 1
With this code you get almost exactly the output you want:
d={}
for a in Book_list.values():
for x,y in a.items():
d[x]=y[1]
print("status=", d)
You could also, of course, assign d
to your a status
variable.
This code just creates first an empty d
as dict and then fills it with data and finally prints it. To fill d
with data, a
, x
and y
take different values while walking (iterating) over your object:
a
: For example {1001: ['Pride and Prejudice', 'available'], 1002: ['Fahrenheit 451', 'available']}
x
: For example 1001
y
: For example ['Pride and Prejudice', 'available']
y[1]
would then be 'available'
Upvotes: 0
Reputation: 10592
Using Python 3.10's structural pattern matching, maybe not super appropriate/helpful for this, but I just wanted to try it :-)
rs = {}
for category in Book_list.values():
for item in category.items():
match item:
case ii, [_, 'available' as status]:
rs[ii] = status
(code adapted from Dani's)
Upvotes: 0
Reputation: 61930
One approach is to use a dictionary comprehension:
rs = {ii : status for category in Book_list.values() for ii, (name, status) in category.items() if status == "available"}
print(rs)
Output
{1001: 'available', 1002: 'available', 2001: 'available', 2002: 'available'}
The above is equivalent to the followings nested for loops:
for category in Book_list.values():
for ii, (name, status) in category.items():
if status == "available":
rs[ii] = status
For understanding the unpacking expressions such as:
# _, category
# ii, (name, status)
you could read this link. For a general introduction to Python's data structures I suggest reading the documentation.
Upvotes: 3
Reputation: 629
def receive_available_books(Book_list):
status = {}
for cat in Book_list.values():
for code, book in cat.items():
status[code] = book[1]
return status
Output:
{1001: 'available', 1002: 'available', 2001: 'available', 2002: 'available'}
Upvotes: 0