简体   繁体   中英

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 keys of the two dictionaries are the same.

dictAvgGrade = {k:sum(v)/4 for k,v in studentPerf.items()}

dictDemClass = {k:0 for k in classes}

When printed (dictAvgGrade is shortened):

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}

Ultimately I want to fill dictDemClass to show the average for each class. So that the output could look something like:

print(dictDemClass)

{'junior': 77.46, 'senior': 83.82, 'sophomore': 86.79}

You can use itertools.groupby to groups items in dictAvgGrade by "class" (ie 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}

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)

Output

{'senior': 0.8087500000000001, 'junior': 0.7862499999999999, 'sophomore': 0}

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

for key in (dictDemClass.keys() & dictAvgGrade.keys()):
    dictDemClass[key] = dictAvgGrade[key]

if you are using python2 you can do something like this

for key in (set(dictDemClass.keys()) & set(dictAvgGrade.keys())):
    dictDemClass[key] = dictAvgGrade[key]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM