You can use dict.setdefault check if a key exists in the dictionary and if not, create new value (in this case empty list []):

d =  {"python" : 1, "is" : 1, "cool" : 2}

reversed_d = {}
for k, v in d.items():
    reversed_d.setdefault(v, []).append(k)

print(reversed_d)

Prints:

{1: ['python', 'is'], 2: ['cool']}

This can be more explicitly rewritten as:

d =  {"python" : 1, "is" : 1, "cool" : 2}

reversed_d = {}
for k, v in d.items():
    if v not in reversed_d:
        reversed_d[v] = [k]
    else:
        reversed_d[v].append(k)

print(reversed_d)
Answer from Andrej Kesely on Stack Overflow
🌐
LabEx
labex.io › tutorials › python-how-to-invert-a-python-dictionary-with-duplicate-values-398217
How to invert a Python dictionary with duplicate values | LabEx
This tutorial will guide you through the process of inverting a Python dictionary with duplicate values, providing practical solutions and examples to help you master this useful technique.
🌐
The Renegade Coder
therenegadecoder.com › code › how-to-invert-a-dictionary-in-python
How to Invert a Dictionary in Python: Comprehensions, Defaultdict, and More – The Renegade Coder
May 21, 2024 - In short, one of the best ways to invert a dictionary in Python is to use a for loop in conjunction with the setdefault method of dictionaries to store duplicate keys in a list.
Discussions

inversing a dictionary in python with duplicate values - Stack Overflow
I need to inverse a dictionary so that each old value will now be a key and the old keys will be the new values. The trick is that there could be multiple values that are the same in the old dictio... More on stackoverflow.com
🌐 stackoverflow.com
python - Reverse / invert a dictionary mapping - Stack Overflow
Especially for a large dict, note ... answer Python reverse / invert a mapping because it loops over items() multiple times. ... This is just plain unreadable and a good example of how to not write maintainable code. I won't -1 because it still answers the question, just my opinion. 2012-10-03T19:19:56.59Z+00:00 ... I am aware that this question already has many good answers, but I wanted to share this very neat solution that also takes care of duplicate values... More on stackoverflow.com
🌐 stackoverflow.com
python - How to reverse a dictionary that has repeated values - Stack Overflow
You may want to use defaultdict(set) and replace append() with add(). This would remove duplicates, but keep uniq values. 2021-07-29T23:01:32.123Z+00:00 ... Note that while it works like charm, this also changes type from dict to defaultdict, so to get a standard Python dictionary object one ... More on stackoverflow.com
🌐 stackoverflow.com
python - how to invert a dictionary with multiple same values? - Stack Overflow
I have a list of words I want to keep in a fast-to-extract data structure, so when a word is queried, I can return all of its anagrams. I thought of a dictionary with {(len, sum) : word} but I'm ha... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Techie Delight
techiedelight.com › home › python › invert mapping of a dictionary in python
Invert mapping of a dictionary in Python | Techie Delight
2 weeks ago - A final way to invert mapping of a dictionary in Python is to use the zip() function with the dictionary constructor. The zip() function takes two or more iterable objects and yields tuples containing corresponding items from each iterable. Here is an example of its usage to invert mapping of a dictionary: ... If the dictionary’s values aren’t unique, we can use a simple for-loop to handle duplicate values in a dictionary.
🌐
LabEx
labex.io › tutorials › invert-dictionary-with-duplicates-13603
Python Dictionary Inversion | Data Structures | LabEx
Use dictionary.items() in combination with a loop to map the values of the dictionary to keys using dict.append(). Use dict() to convert the collections.defaultdict to a regular dictionary. Function signature: def invert_dictionary(obj: dict) -> dict:
🌐
Iditect
iditect.com › faq › python › reverse--invert-a-dictionary-mapping-in-python.html
Reverse / invert a dictionary mapping in python
Description: Inverting a dictionary with duplicate values requires handling those duplicates appropriately, often by storing them as lists.
Find elsewhere
🌐
w3resource
w3resource.com › python-exercises › dictionary › python-data-type-dictionary-exercise-67.php
Python: Invert a given dictionary with non-unique hashable values - w3resource
June 28, 2025 - Write a Python program to invert a dictionary so that each value maps to a list of keys using collections.defaultdict. Write a Python program to iterate over a dictionary and build an inverted dictionary where duplicate values become keys with list of original keys.
🌐
Reddit
reddit.com › r/learnpython › reverse keys and values in a dictionary
r/learnpython on Reddit: Reverse keys and values in a dictionary
April 19, 2022 -

Hi y'all!

While doing the 'Invert a dictionary' in the Python MOOC (https://programming-21.mooc.fi/part-5/3-dictionary), I couldn't reverse the dictionary, with the global variable unable to be changed when used into the function.

Here is my code:

def invert(dictionary: dict):    new_dict = {}for key, value in dictionary.items():        new_dict[value] = key

dictionary.clear()

dictionary = new_dictif __name__ == '__main__':    s = {1: "first", 2: "second", 3: "third", 4: "fourth"}    invert(s)print(s)

The output is the same before and after the function is called. I think it's a problem with the reference. Could you please help me with this exercise?

Edit: I'm still not using list and dict comprehension, so I would appreciate if you could do it with loops. Thanks!

🌐
ActiveState
code.activestate.com › recipes › 252143-invert-a-dictionary-one-liner
Invert a dictionary (one-liner) « Python recipes « ActiveState Code
November 17, 2003 - assert len(inverted_dict) == len(mydict), 'duplicate value in mydict' ... If you need to maintain the inverse mapping across many updates and changes, then these one-shot one-liners must be re-computed many times. To cope with that situation, I just added Recipe 576968 with a python dict subclass.
🌐
Thelightech
thelightech.com › home › blog › for developers › how to change keys and values in a python dictionary
How to swap keys and values in a Python dictionary — a task from an interview | LighTech
In the implementation variant invert_dictionary_comprehension will silently overwrite values if the original values are duplicated, it does not check for hashability until a key creation is attempted. For an interview, it would be better to show a more elaborate version with checks first.
🌐
Pierian Training
pieriantraining.com › home › reversing keys and values in a python dictionary
Reversing Keys and Values in a Python Dictionary - Pierian Training
April 28, 2023 - It’s important to note that if there were any duplicate values in the original dictionary, they would have been overwritten in the reversed dictionary since dictionaries cannot contain duplicate keys. Reversing Keys and Values in a Python Dictionary – Conclusion
🌐
Delft Stack
delftstack.com › home › howto › python › python invert a dictionary
How to Reverse a Dictionary in Python | Delft Stack
February 2, 2024 - In summary, use items() to loop over the dictionary and invert the keys and values. If by any chance your data set is likely to have duplicates, then make sure to convert the values into a list by using defaultdict() and manipulate it in a way ...
🌐
DEV Community
dev.to › therenegadecoder › how-to-invert-a-dictionary-in-python-2150
How to Invert a Dictionary in Python: Comprehensions, Defaultdict, and More - DEV Community
August 8, 2020 - In other words, Python doesn’t allow lists to be keys in dictionaries because lists are not immutable. Fortunately, it’s easier to revert our dictionary than it was to invert it in the first place. We can use the following dictionary comprehension: my_dict = {value: key for key in my_inverted_dict for value in my_map[key]} As we can see, we make a new key-value pair for every single value in each list using this double loop structure.
🌐
py4u
py4u.org › blog › python-reverse-inverse-a-mapping-but-with-multiple-values-for-each-key
How to Reverse or Inverse a Python Dictionary with Multiple Values per Key: A Complete Guide
Test with Edge Cases: Verify behavior with empty dictionaries, mixed values, and duplicates. Inverting a Python dictionary with multiple values per key requires careful handling of iterable values and duplicate entries. The collections.defaultdict method stands out as the most efficient and readable solution, automating key initialization and simplifying code.
🌐
30 Seconds of Code
30secondsofcode.org › home › python › invert a dictionary
Python - Invert a dictionary - 30 seconds of code
May 8, 2024 - You can invert a dictionary with non-unique hashable values, using some simple Python code.
🌐
GeeksforGeeks
geeksforgeeks.org › python-ways-to-invert-mapping-of-dictionary
Python | Ways to invert mapping of dictionary - GeeksforGeeks
April 27, 2023 - Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Let's discuss a few ways to invert mapping of a ...