Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Q1. Write a function to build a dictionary from two lists of equal length. One o

ID: 3834340 • Letter: Q

Question

Q1. Write a function to build a dictionary from two lists of equal length. One of the lists should contain elements that will serves as keys and the other list should contain elements that will serve as values.

Run your code to demonstrate that it works. Include the output in your answer. The output should show the two starting lists and the resulting dictionary.

What happens if the lists should chance to be of unequal length?


Q2. Now write a function that will do the inverse of the operation above i.e. this function takes a dictionary and returns two lists, one list containing keys and the other list containing values.

Can you really return two independent lists (i.e. can a function return two values)? How will you resolve this problem?

Run your code to demonstrate that it works. Include the output in your answer. The output should show the starting dictionary and the two resulting lists.

Explanation / Answer

1.

#method 1

def listToDict(keys,values):
   return dict(zip(keys,values))
keys = [0, 1, 2, 3, 4]
values = [0, 1, 2, 3, 4, 5, 6]
print listToDict(keys,values)
print listToDict(values,keys)

#method 2

def listsToDict1(keys,values):
   res = {}
   for i in range(min(len(keys), len(values))):
       res[keys[i]] = values[i]
   return res
print listsToDict1(keys,values)
print listsToDict1(values,keys)

it will pick list with minimum lenght and make dict but if you have more keys and less values you can store null for extra keys by iterating till length of key in 2nd method using conditions like if i > len(values) res[keys[i]] = ""

Q2-

def dcitToList(dicts):
   return dicts.keys(),dicts.values()

print dcitToList({0: 0, 1: 1, 2: 2, 3: 3, 4: 4})