PYTHON PROBLEM Current functions for the question: def reviewer_rank(db : {str:{
ID: 3591663 • Letter: P
Question
PYTHON PROBLEM
Current functions for the question:
def reviewer_rank(db : {str:{(str,int)}}) -> [(str,int)]:
pass
def reviewer_nested_dict(db : {str:{(str,int)}}) -> {str:{str:int}}:
pass
Explanation / Answer
Hello there,
yes ,you are correct we should use defaultdict(from collections library).
Below is my python code with sample data i took from your question.
Feel free to ask any questions if necessary.
i have used counter and defaultdict functions from Collections package in the code.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from collections import Counter
from collections import defaultdict
dic = {'psycho':{('bob',1),('carry',3),('dianne',4)},
'amedus': {('don',1),('bob',3),('asz',4)}}
def reviewer_rank(db):
main_l=[] #creating List containing all the persons name across movies
for i in dic.values():
temp_l = list(i)
temp_l=dict(temp_l).keys() #getting only the name from the tuple (name,score)
main_l.extend(temp_l) #appending it in list
counter=Counter(main_l # using counter to count frequency of the list
counter=sorted(counter.items(), key=lambda i: i[1], reverse=True) #sorting the list, if u want ascending sort put reverse=False)
return counter
reviewer_rank(dic)
Output:
[('bob', 2), ('don', 1), ('asz', 1), ('carry', 1), ('dianne', 1)]
def reviewer_nested_dict(db):
raters = defaultdict(dict)
for movie, scores in dic.items():
for name, score in scores:
raters[name][movie] = score
return(dict(raters))
reviewer_nested_dict(dic)
Output:
{'asz': {'amedus': 4},
'bob': {'amedus': 3, 'psycho': 1},
'carry': {'psycho': 3},
'dianne': {'psycho': 4},
'don': {'amedus': 1}}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.