How do i invert a dictionary while keeping ALL the original keys as values?
I need a function to do the following:
▪︎occupations = {"matt": "waiter", "john": "student", "sarah": "student"}
▪︎occupations_reversed = {"waiter": "matt", "student": #john, sarah #[john, sarah] #(john, sarah)}
I tried using:
occupations_reversed = {value: key for key, value in occupations.items()} #but once it finds "student" again it just overwrites whatever was saved (i.e. "john")
occupations_reversed . . . {"waiter": "matt", "student": "sarah"} #so it doesn't work :(
Posted Feb 6, 2022, 5:46 PM UTC
16
Start by defining the desired result more clearly. What's
#john, sarah #[john, sarah] #(john, sarah)? In fact,"waiter": "matt"doesn't really fit what you probably want either, if you really think about it.