Feedback needed/appreciated - Potus datatset - Visitor who spent the most amount of time at the White House

Screen Link:
https://app.dataquest.io/c/62/m/353/working-with-dates-and-times-in-python/11/next-steps

My Code:

amount_of_time = {}

for row in potus:
    name = row[0]
    
    # duration of each single meeting in timedelta type
    meeting_len = row[3] - row[2]

    # duration in seconds
    meeting_len = meeting_len.seconds

    amount_of_time[name] = amount_of_time.get(name, 0) + meeting_len

# temporary dictionary to invert key and values
tmp = {}
for k, v in amount_of_time.items():
    tmp[v] = k

# find the largest amount of seconds that now is a key
longest_time = max(tmp)
visitee = tmp[longest_time]
print(f"The visitee who spent the most time at the white house is {visitee.title()}")

Please note that I haven’t included in the code all the code to read in the CSV file. Also the appt_start_date and appt_end_date were already in the datetime type.

It seems to be working ok, and I would like to have feedback if there is something that should be improved.

My main concern with the technique I used, is that if by any change two or more people have visited the white house the same amount of time, this code will only “return” the first one that happen to be before in the dictionary.

How could that be fixed? I seem not to wrap my head around that :sweat_smile:

Thanks in advance everyone.

PS: this is like my first post in the community (apart from a short presentation) so if there is anything I did wrong please let me know.

Thanks again

Welcome @polUSA

I have found your code and the truth is that it has made me think more than I thought! :sweat_smile:

For what I’ve been searching, and as the solution is not mine I prefer to pass you the link where I found it:

ACERVO LIMA

There are several techniques: :thinking:

  • The naïve method
  • Flipping dictionary
  • String and set

What I have done has been to adapt the solution that I have found, the technique I have used has been the first:

# below your code
repeated_values = {}

for key, value in tmp.items():
    repeated_values.setdefault(value, set()).add(key)

result = [key for key, values in repeated_values.items() 
                              if len(values) > 1] 
  
print("duplicate values", str(result))

I hope it serves to you, if so I invite you to indicate that it is resolved. Otherwise I apologize and if so let me know.

A&E