Skip to content

Commit af8332e

Browse files
authored
Create unit8_ex8.3.4.py
1 parent 9b4232f commit af8332e

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

unit8_ex8.3.4.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# exercies 8.3.4 from unit 8
2+
'''
3+
We are nearing the end of the course and at this stage you can combine the topics
4+
learned throughout the course, explore additional options yourself and apply everything
5+
in writing the code.
6+
7+
In this exercise, write a function called inverse_dict defined as follows:
8+
9+
def inverse_dict(my_dict):
10+
The function accepts as a parameter a dictionary.
11+
The function returns a new dictionary with a "reverse" mapping: each key in the passed
12+
dictionary is a value in the returned dictionary and each value in the passed dictionary
13+
is a key in the returned dictionary.
14+
15+
Guidelines
16+
17+
The inversion between keys and values may create keys that appear more than once. Therefore,
18+
display the values in the returned dictionary as a list, which may contain one or more values
19+
The returned lists should be sorted (it can be assumed that the values in the dictionary
20+
are of the same type).
21+
22+
'''
23+
24+
def main():
25+
def inverse_dict_helper(my_dict):
26+
inverted_dict = {}
27+
for key, value in my_dict.items():
28+
if value not in inverted_dict:
29+
inverted_dict[value] = [key]
30+
else:
31+
inverted_dict[value].append(key)
32+
for value in inverted_dict.values():
33+
value.sort()
34+
return inverted_dict
35+
36+
my_dict = {'a': 1, 'b': 2, 'c': 1, 'd': 2, 'e': 2}
37+
print(inverse_dict_helper(my_dict))
38+
39+
main()
40+

0 commit comments

Comments
 (0)