Student Name
Institution Name
Course Number
Due Date
Faculty Name
Part 1
Code
# Defining a function that will inverse a dictionary.
def invert_dict(d):
inverse = dict() # dictionary for storing the inverse.
# begin the loop for transversing the dictionary
for key in d.keys():
values = d[key]
# loop used for transversing the values
for value in values:
if value not in inverse:
inverse[value] = [key]
# append the values to the key
else:
inverse[value].append(key)
return inverse
# main() function
def main():
dic = {'b': ["bees", "bread"], 'c': ["cat"]}
print("Original dictionary:") # to diplay the original dictionary
print(dic)
# inverted dictionary being displayed
print("\nInverted dictionary:")
print(invert_dict(dic))
# main() function being called
if __name__ == "__main__":
main()
Output
Explanation
The inverted dictionary was not so helpful given that a dictionary is mainly used to map key-values pairs. The common attributes of the distinct values are mapped to the key. The value is mapped on a single key. The inverted dictionary had inverted key value pairs. The value is similar to the keys which are composed from the list of values from the original dictionary. For instance ‘bees’ and ‘bread’ had similar value ‘b’ given that they were developed from the list of values of similar key. It aids in making easy to identify keys with similar values within a dictionary.
Part 2
Tuples are used to store the related attributes in one object even without developing a custom class. For instance if want to store the name and the ages of three individuals together, we can store them in a list of tuples.
Code
dt = [('Wendy', 11), ('Mark ', 20), ('Jane', 50)]
# to print every person's age
for (name, age) in dt:
print(name, 'is', age, 'years old')
#2 lists are zipped together using the zip function
names = ['Wendy', 'Mark', 'Jane']
ages = [11, 20, 5]
#similar output can be generated using this code
for (name, ages) in zip(names, ages):
print(name, 'is', ages, 'years old')
#use of the enumerate function to provide the indices for each element
for (index, name) in enumerate(names):
print(index, ':', name)
# item method used in dictionary
ageDict = {'Wendy': 11, 'Mark': 20, 'Jane': 50}
for (name, agess) in ageDict.items():
print(name, 'is', agess, 'years old')
Output