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
alexmojaki•

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.

3
wbeater•

Expected behavior, keys in a dictionary have to be unique. A dictionary comprehension won't do it.

2
ElliotDG•

Here is one way to do it, making each value in the new dict a list.

occupations = {"matt": "waiter", "john": "student", "sarah": "student"}
reversed_occupations = {}

for name, job in occupations.items():
    reversed_occupations.setdefault(job, []).append(name)

print(reversed_occupations)

output:

{'waiter': ['matt'], 'student': ['john', 'sarah']}
1
user4288OP•

This! Thank you :)

1
[deleted]•

[deleted]

1
rbn93•
reverse ={}
for key,value in my_dict.items():
    if value in reverse.keys():
        old_key= reverse[value]
        if type(old_key) == str:
            reverse[value] = [old_key, key]
        else:
            reverse[value].append(key)
    else:
        reverse[value] = key
1
user4288OP•

Thank you for the help :D

1