How to reverse a dictionary (whose values are lists) in Python?
You can do it very simply like this:
newdict = {}
for key, value in olddict.items():
for string in value:
newdict.setdefault(string, []).append(key)
How I reverse a dict:
def reverse(org):
return {v: k for k, v in org.items()}
print(reverse({1: 'a', 2: 'b'}))
# {'a': 1, 'b': 2}
Use a dict comprehension!
>>> evil_petting_zoo = {'bear':3, 'crocodile':1,'kangaroo':2,'goat':0}
>>> evil_petting_zoo.items()
dict_items([('bear', 3), ('crocodile', 1), ('kangaroo', 2), ('goat', 0)])
>>> {i[1]:i[0] for i in evil_petting_zoo.items()}
{3: 'bear', 1: 'crocodile', 2: 'kangaroo', 0: 'goat'}
TL;DR:
{i[1]:i[0] for i in myDictionary.items()}
I would begin by swapping the keys/values using a default dict:
output_dict = defaultdict(list)
for key, values in input_dict.items():
for value in values:
output_dict[value.lower()].append(key.lower())
And finally sorting:
for key, values in output_dict.items():
output_dict[key] = sorted(values)