How Do I Fill My Dictionary Values With The Values From Another Dictionary Where Their Keys Are The Same?
I have one dictionary (dictDemCLass) with a key but the values are all 0 and I plan to fill them with the values from another dictionary (dictAvgGrade). I need to do so where the
Solution 1:
You can use itertools.groupby to groups items in dictAvgGrade by "class" (i.e. junior, senior, etc.). Then you can compute the average for each group and add it to dictDemClass.
So for the example your posted, it can be something like the following:
from itertools import groupby
dictAvgGrade = {('Jeffery', 'male', 'junior'): 0.7749999999999999, ('Able', 'male', 'senior'): 0.8200000000000001, ('Don', 'male', 'junior'): 0.7974999999999999, ('Will', 'male', 'senior'): 0.7975000000000001}
dictDemClass = {'junior': 0, 'senior': 0, 'sophomore': 0}
defget_class(x):
return x[0][2]
for k, g in groupby(sorted(dictAvgGrade.items(), key=get_class), key=get_class):
group = list(g)
class_avg = sum(x[1] for x in group)/len(group)
dictDemClass[k] = class_avg
print(dictDemClass)
Output
{'senior': 0.8087500000000001, 'junior': 0.7862499999999999, 'sophomore': 0}
Solution 2:
if you know that dictAvgGrade is always a subset of dictDemClass you can do this
dictDemClass.update(dictAvgGrade)
otherwise
if you are using python3 you can do something like this
forkeyin (dictDemClass.keys() & dictAvgGrade.keys()):
dictDemClass[key] = dictAvgGrade[key]
if you are using python2 you can do something like this
forkeyin (set(dictDemClass.keys()) & set(dictAvgGrade.keys())):
dictDemClass[key] = dictAvgGrade[key]
Post a Comment for "How Do I Fill My Dictionary Values With The Values From Another Dictionary Where Their Keys Are The Same?"