Home > Software engineering >  Delete item in dict with variable
Delete item in dict with variable

Time:12-09

I've been having another problem. I have been trying to delete a value in a dict using a string. I thought this would be possible, as I tried it with just a plain string and it worked.

waiting_list = []
waiting_room = {
    'John': '123',
    'Bob': '124'
}
patient_delete = input('which patient would you like to delete? ')
for patient_delete in waiting_room:
    del waiting_room[patient_delete]
    del waiting_list[patient_delete]

If it helps, it threw this error at me after.

TypeError: list indices must be integers or slices, not str.

Thank you to anyone that helps!

CodePudding user response:

I think you'll want:

waiting_list = []
waiting_room = {
    'John': '123',
    'Bob': '124'
}
patient_delete = input('which patient would you like to delete? ')
if patient_delete in waiting_room:
    # remove from dictionary
    del waiting_room[patient_delete]

if patient_delete in waiting_list:
    # remove from list (pop would also work on the dict)
    waiting_list.pop(waiting_list.index(patient_delete))

    # or alternatively using remove method
    #waiting_list.remove(patient_delete)
  • Related