Question: please help I dont understand how to do this question must use try and except in python code cheers Consider the following graph: We could
please help I dont understand how to do this question must use try and except in python code cheers


Consider the following graph: We could represent this graph using key-value pairs as follows: 1: [2, 3] 2: [1, 3, 5] 3: [4, 5] 4: [] 5: [4] The numbers represent the nodes, and the list associated with a given key records the nodes that the key connects to in the graph. We could store this arrangement of data in a dictionary. To add an element to the dictionary, we use the following function: def add_to_list_in_dict(a_dict, list_name, element): if list_name in a_dict: a_dict [list_name].append(element) else: a_dict(list_name] = [element] Currently, this function will allow any type of value to be used to represent the name of the node. However, we would like to restrict the type of the data so that only integer values can be used as the name of the node (i.e., as the dictionary keys, or as elements in the lists). Modify this function so it will run successfully regardless of the type of data passed as the name of a node, but print out an appropriate error if the data cannot be converted to an integer using the int() function. If the name of the key is invalid, then the function should print "ERROR: Cannot create list 'XXX' where XXX is the invalid data passed If the element is invalid, then the function should print "ERROR: Invalid element!" You *must* use the try... except syntax in your solution. For example: Test Result my_dict = {3: [1]} 3: [1, 2] add_to_list_in_dict(my_dict, 3, 2) for key in sorted(my_dict.keys()): print('{}: {}'.format(key, my_dict[key])) my_dict = {1: [2, 3], 2: [1, 3, 5), 3: [4, 5], 4: [], 5: [4]} ERROR: Cannot create list 'a' add_to_list_in_dict(my_dict, 'a', 4) 1: [2, 3] for key in sorted (my_dict.keys()): 2: [1, 3, 5] print('{}: {}'.format(key, my_dict[key])) 3: [4, 5] 4: [] 5: [4] my_dict = {1: [2, 3], 2: [1, 3, 5), 3: [4, 5], 4: [], 5: [4]} ERROR: Invalid element ! add_to_list_in_dict(my_dict, 4, 'a') 1: [2, 3] for key in sorted (my_dict.keys(): 2: (1, 3, 5] print('{}: {}'.format(key, my_dict [key])) 3: [4, 5] 4: [] 5: [4] Answer: (penalty regime: 0, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 %) 1
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
