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.
CodePudding user response:
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.
CodePudding user response:
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'}
CodePudding user response:
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)