How to remove values that are in another list?

Asked

Viewed 66 times

1

I have two dictionaries, one with available schedules, and one with scheduled schedules:

schedules_dict = {1: ['00:00'], 2: ['00:30', '00:45'], 3: ['00:00', '00:30', '00:45']}
appointments_dict = {1: ['00:00'], 2: ['00:30'], 3: ['00:00', '00:30']}

And I need to show only the times that are still available:

output = {2: ['00:45'], 3: ['00:45']}

Trying:

for key in schedules_dict.keys():
    if key in appointments_dict.keys():            
        print(key)

3 answers

1

An alternative is to turn the time lists into set's and subtract them. So what’s left are the available times:

schedules_dict = {1: ['00:00'], 2: ['00:30', '00:45'], 3: ['00:00', '00:30', '00:45']}
appointments_dict = {1: ['00:00'], 2: ['00:30'], 3: ['00:00', '00:30']}

output = {}
for indice, disponiveis in schedules_dict.items():
    if indice in appointments_dict:
        # vê os horários que sobraram
        sobrou = list(set(disponiveis) - set(appointments_dict[indice]))
        if len(sobrou) > 0:
            output[indice] = sobrou
    else:
        output[indice] = disponiveis

print(output) # {2: ['00:45'], 3: ['00:45']}

One detail is that set does not guarantee the order of the elements. If you want the times to be in order, just change to use sorted:

sobrou = sorted(set(disponiveis) - set(appointments_dict[indice]))

At first, compare strings containing digits does not always work as expected, but in this case the times are in HH:MM format (always with 2 digits, according to the ISO 8601 standard), then the ordering is done correctly.

1

see if this helps you:

schedules_dict = {1: ['00:00'], 2: ['00:30', '00:45'], 3: ['00:00', '00:30', '00:45']}
appointments_dict = {1: ['00:00'], 2: ['00:30'], 3: ['00:00', '00:30']}
for key in schedules_dict:
    for i in schedules_dict[key]:
        if i not in appointments_dict[key]:
            print(key,i)

-1

Just strengthening the understanding.

You can consult the Python help utility if you need more guidance about this function

just enter the interactive shell and type:

help(set())

help ("something you need to know")

You’ll have more help.

More information

Browser other questions tagged

You are not signed in. Login or sign up in order to post.