-
Notifications
You must be signed in to change notification settings - Fork 59
/
Inverse_Dict.Py
52 lines (43 loc) · 912 Bytes
/
Inverse_Dict.Py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
'''If any key-value dictionary is made,
and we want to make inverse of dictionary.
A value can have different keys,
so in inverse dictionary ,
all keys are stored in a list'''
def make_dict(string):
d=dict()
for c in string:
d[c]=d.get(c,0)+1
return d
def print_dict(d):
print("Key\tValue")
for key in d:
print(key,'\t',d[key])
def inverse_dict(d):
inverse=dict()
for key in d:
val=d[key]
if val not in inverse:
inverse[val]=[key]
else:
inverse[val].append(key)
return inverse
string='parrot'
d=make_dict(string)
print("Dictionary:")
print_dict(d)
inv=inverse_dict(d)
print("Inverse Dictionary:")
print_dict(inv)
'''-----------------------Output------------
Dictionary:
Key Value
p 1
a 1
r 2
o 1
t 1
Inverse Dictionary:
Key Value
1 ['p', 'a', 'o', 't']
2 ['r']
'''