Complete function def categorize (Dictionary, str): -> Dictionary
where str is the key that is categorized.
Original Dictionary: {'Math': {'Mark': '92', 'Name': 'John', 'Suggestion': 'excellent'}, 'English': {'Mark': '41', 'Name': 'Steve', 'Subject': 'English', 'Suggestion': 'retake'}, 'Science': {'Mark': '91', 'Name': 'Taylor', 'Suggestion': 'excellent'}}
Suppose str is Suggestion.
Function categorize should produce {'excellent': ['Math', 'Science'], 'retake': ['English']}
Source Code in Python:
def categorize(Dict,s):
newDict={} #creating black dictionary to store result
for i in Dict: #iterating through the outer dictionary
for j in Dict[i]: #iterating through each inner dictionary
if j==s: #if any of the inner dictionary keys match the given
string
if newDict.get(Dict[i][j],-1)==-1: #we check if a list already
exists for the key
newDict[Dict[i][j]]=[i] #we create a new list
else:
newDict[Dict[i][j]].append(i) #else we append to existing
list
return newDict #returning result
#creating dictionary for the function
Dict={'Math': {'Mark': '92', 'Name': 'John', 'Suggestion':
'excellent'},
'English': {'Mark': '41', 'Name': 'Steve', 'Subject': 'English',
'Suggestion': 'retake'},
'Science': {'Mark': '91', 'Name': 'Taylor', 'Suggestion':
'excellent'}}
#testing the function
print(categorize(Dict,"Suggestion"))
print(categorize(Dict,"Subject"))
print(categorize(Dict,"Name"))
Output:
Complete function def categorize (Dictionary, str): -> Dictionary where str is the key that is categorized....