-
Notifications
You must be signed in to change notification settings - Fork 0
/
sgt_20220926_dict_exer3.py
43 lines (29 loc) · 1.47 KB
/
sgt_20220926_dict_exer3.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
# # 3. Dictionary cleaner
# 3a. Write clean_dict_value(d, bad_val), which returns a cleaned dictionary without any keys with
# the value bad_val
# The parameters of the function are the dictionary d to be processed and the value bad_val
# to be disposed of together with its key.
# Example:
# clean_dict_value ({'a': 5, 'b': 6, 'c': 5}, 5) -> {'b': 6}, because 5 was a value for both a and c keys to get rid of.
# 3b Write clean_dict_values (d, v_list), which returns a cleaned dictionary
# The parameters of the function are the dictionary d to be processed and the list of values
# v_list to get rid of.
# clean_dict_values ({'a': 5, 'b': 6, 'c': 5, 'd':3}, [3,4,5]) -> {'b': 6}
# because 3 and 5 were in the list of values to delete.
# PS. Remember we can use del d['a'] only if the key 'a' exists.
# !! When resizing a dictionary, we are not allowed to iterate at the same time!
# There are two options: either walk through the copy my_dict.copy.items(), or build a new dictionary.
# Dictionary comprehension would be one option.
def replace_dict_value(d, bad_val, good_val):
new_dict = {}
for key, value in d.items():
if value != bad_val:
new_dict[key] = value
if value == bad_val:
new_dict[key] = good_val
return new_dict
print(replace_dict_value({'a': 5, 'b': 6, 'c': 5}, 5, 30))
my_dict = {'a': 5, 'b': 6, 'c': 5, 'd':3, 'e': 5, 'f': 5, 'g':8}
new_dict = replace_dict_value(my_dict, 8)
print(new_dict)
print(my_dict)