PPA-5
Question
Write the following functions:
dict_to_list: accept a dictionaryDas argument. Return the key-value pairs inDas a listLof tuples. That is, every element ofLshould be of the form(key, value)such thatD[key] = value. Going the other way, every key-value pair in the dictionary should be present as a tuple in the listL.list_to_dict: accept a list of tuplesLas argument. Each element ofLis of the form(x, y). Return a dictDsuch that each tuple(x, y)corresponds to a key-value pair inD. That is,D[x] = y.
- For the function
dict_to_list, the order in which the key-value pairs are appended to the list doesn’t matter. - For the function
list_to_dict, you can assume that if(x1, y1)and(x2, y2)are two different elements inL,x1 != x2. Why is this assumption important? - You do not have to accept input from the user or print the output to the console. You just have to write the definition of both the functions.
Hint
- For the function
dict_to_list, executelist(D.items())and observe what you get. - For the function
list_to_dict, executedict(L)and observe what you get.
Solutions
Refer to this document and this document for more details regarding some aspects of dictionaries.