In: Computer Science
The dictionary is the most natural data structure to hold the apple information from the previous lesson. Below are the parallel arrays that track a different attribute of the apples (note that the above chart (Sweet-Tart Chart) doesn't align with the data from the previous lesson):
names = ["McIntosh", "Red Delicious", "Fuji", "Gala", "Ambrosia", "Honeycrisp", "Granny Smith"]
sweetness = [3, 5, 8, 6, 7, 7.5, 1]
tartness = [7, 1, 3, 1, 1, 8, 10]
Step 1: Data Model (parallel arrays to dictionary)
Build a dictionary named apples. The apple dictionary keys will be the names of the apples. The values will be another dictionary. This value dictionary will have two keys: "sweetness" and "tartness". The values for those keys will be the respective values from the sweetness and tartness lists given above. You will build this by defining a variable named apples (see the complex_map example).
Step 2: Apple Aid
Now that we have our model, create a function named by_sweetness whose parameter will be a tuple (from apples.items()) The function by_sweetness will return the sweetness value of the incoming tuple. This helper function cannot reference the global variable apples (from step 1).
Step 3: Apple Sorting
Write a function called apple_sorting that has two parameters: data (the data model) and sort_helper (the function used to sort the model). The apple_sorting should use the sorted function to sort the data (e.g. data.items()) with sort_helper. The function returns a list of tuples in order of their sweetness (sweetest apples listed first).
Once done, this should work:
print(apple_sorting(apples, by_sweetness))
Please find the solution below. Let me know if you have any doubt. names = ["McIntosh", "Red Delicious", "Fuji", "Gala", "Ambrosia", "Honeycrisp", "Granny Smith"] sweetness = [3, 5, 8, 6, 7, 7.5, 1] tartness = [7, 1, 3, 1, 1, 8, 10] apples={} for i in range(len(names)): inner_dict={} inner_dict[('sweetness','tartness')]=(sweetness[i],tartness[i]) apples[names[i]]=inner_dict #by_sweetness function which return the sweetness value of the incoming tuple. def by_sweetness(tup): for key, val in tup[1].items(): return val[0] for ele in apples.items(): print('Sweetness for',ele[0],'is',by_sweetness(ele))
Output: