![](/img/trans.png)
[英]how to fill dictionary values with the counts of similar keys in another dictionary
[英]How do I fill my dictionary values with the values from another dictionary where their keys are the same?
我有一個帶鍵的字典(dictDemCLass),但值全為0,我打算用另一字典(dictAvgGrade)的值填充它們。 在兩個字典的鍵相同的地方,我需要這樣做。
dictAvgGrade = {k:sum(v)/4 for k,v in studentPerf.items()}
dictDemClass = {k:0 for k in classes}
打印時(dictAvgGrade縮短了):
print(dictAvgGrade)
{('Jeffery', 'male', 'junior'): 0.7749999999999999, ('Able', 'male', 'senior'): 0.8200000000000001, ('Don', 'male', 'junior'): 0.7974999999999999, ('Will', 'male', 'senior'): 0.7975000000000001}
print(dictDemClass)
{'junior': 0, 'senior': 0, 'sophomore': 0}
最終,我想填充dictDemClass來顯示每個類的平均值。 這樣輸出結果可能類似於:
print(dictDemClass)
{'junior': 77.46, 'senior': 83.82, 'sophomore': 86.79}
您可以使用itertools.groupby
將dictAvgGrade
的項目按“類”分組(即,初級,高級等)。 然后,您可以計算每個組的平均值並將其添加到dictDemClass
。
因此,對於您發布的示例,它可能類似於以下內容:
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}
def get_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)
輸出量
{'senior': 0.8087500000000001, 'junior': 0.7862499999999999, 'sophomore': 0}
如果您知道dictAvgGrade
始終是dictDemClass
的子集, dictDemClass
可以執行此操作
dictDemClass.update(dictAvgGrade)
除此以外
如果您使用的是python3,則可以執行以下操作
for key in (dictDemClass.keys() & dictAvgGrade.keys()):
dictDemClass[key] = dictAvgGrade[key]
如果您使用的是python2,則可以執行以下操作
for key in (set(dictDemClass.keys()) & set(dictAvgGrade.keys())):
dictDemClass[key] = dictAvgGrade[key]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.