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 Overflowinversing a dictionary in python with duplicate values - Stack Overflow
python - Reverse / invert a dictionary mapping - Stack Overflow
python - How to reverse a dictionary that has repeated values - Stack Overflow
python - how to invert a dictionary with multiple same values? - Stack Overflow
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)
You can use a defaultdict to avoid the pre-fill step
from collections import defaultdict
def inverse_dict(my_dict: dict):
new_dict = defaultdict(list)
for k, v in my_dict.items():
new_dict[v].append(k)
return new_dict
Python 3+:
inv_map = {v: k for k, v in my_map.items()}
Python 2:
inv_map = {v: k for k, v in my_map.iteritems()}
Assuming that the values in the dict are unique:
Python 3:
dict((v, k) for k, v in my_map.items())
Python 2:
dict((v, k) for k, v in my_map.iteritems())
Using collections.defaultdict:
from collections import defaultdict
reversed_dict = defaultdict(list)
for key, value in mydict.items():
reversed_dict[value].append(key)
reversed_dict = {}
for key, value in mydict.items():
reversed_dict.setdefault(value, [])
reversed_dict[value].append(key)
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!
Dictionary keys can't be lists but it can be tuples. So you can do something like below. Sort the values, make them tuples to use as keys and use dict.setdefault:
out = {}
for k,v in dict_1.items():
out.setdefault(tuple(sorted(v)), set()).add(k)
Output:
{('James', 'Lydia', 'Michael'): {('Chemstry', 'Physics'), ('Math', 'English')},
('Tom',): {('Geology', 'PE')},
(): {('Music', 'Psychology'), ('Politics', 'Acting')}}
As told in the question comments lists are unhashable. if you can use tuple instead, "Dict Comprehensions" is a good way. More info: https://www.python.org/dev/peps/pep-0274/.
dict_reverse = {tuple(dict_1[key]): key for key in dict_1.keys()}