Write python code to invert a dictionary, it should print a dictionary where the keys are values from the input dictionary and the values are lists of keys from the input dictionary having the same value. Make sure the program handles multiple same values.
Original Dictionary ::
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value1', 'key5': 'value3'}
New dictionary :
{'value1': ['key1', 'key4'], 'value2': ['key2'], 'value3': ['key3', 'key5']}
python, dictionary, python program, invert a dictionary,
Solution:
dic = {'key1':'value1', 'key2':'value2',
'key3':'value3', 'key4':'value1',
'key5':'value3'}
print("Original Dictionary :: ")
print(dic)
newdic={}
for v in dic.values():
if v not in newdic:
l = []
for k in dic:
if dic[k]== v:
l.append(k)
newdic[v]=l
print("New dictionary : ")
print(newdic)