I'm trying to iterate through my list of dictionaries, for when the user selects a corresponding ID will copy it to the other list.
allBooks =[
{'ID': 101, 'title': 'Meditations', 'author': 'Marcus Aurelius', 'year': 180, 'status': True},
{'ID': 102, 'title': 'To Kill a Mockingbird', 'author': 'Harper Lee', 'year': 1960, 'status': True},
{'ID': 103, 'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald', 'year': 1925, 'status': True},
{'ID': 104, 'title': 'Don Quixote', 'author': 'Miguel de Cervantes', 'year': 1615, 'status': True},
{'ID': 105, 'title': 'The Little Prince', 'author': 'Antoine de Saint-Exupery', 'year': 180 , 'status': True}
]
booksCheckedOut = []
def menu2():
os.system('clear')
for dic in allBooks:
print(dic)
option = input('\nIf You Want To Go Back Type 0\n\nWhat is the ID? ')
# Going back to Main Menu
if option == '0':
return main_menu()
# If User Proceeds with Checking in
else:
for dic in booksCheckedOut:
for k, v in dic.items():
if option == v:
booksCheckedOut.copy(dic)
return menu2()
else:
return menu2()
my expected output would take me back to main_menu()
and copy over the user selected dictionary
booksCheckedOut =['ID': 101, 'title': 'Meditations', 'author': 'Marcus Aurelius', 'year': 180, 'status': True}]
CodePudding user response:
You don't need to loop through the dictionary items. Just compare the ID with what the user entered.
You shouldn't return when the ID doesn't match in the loop, because you need to keep looking.
Don't use recursive calls as a replacement for looping. If you want to go back to the main menu, just return from this (I assume it's called from main_menu()
). And to ask for another book, just wrap this code in a loop.
def menu2():
while True:
os.system('clear')
for dic in allBooks:
print(dic)
option = input('\nIf You Want To Go Back Type 0\n\nWhat is the ID? ')
# Going back to Main Menu
if option == '0':
return
# If User Proceeds with Checking in
else:
id = int(option)
for dic in booksCheckedOut:
if dic['ID'] == id:
booksCheckedOut.append(dic)
break
print(f"ID {id} not found")