The goal of the function is to make a grade adjustment based off of a dictionary and list. For instance
def adjust_grades(roster, grade_adjustment)
adjust_grades({'ann': 75, 'bob': 80}, [5, -5])
will return
{'ann': 80, 'bob': 75}
I just need a nudge in the right direction, I'm new to Python so I thought to put a nested for loop for each num in grade_adjustment but its not the right way.
4 Answers 4
Assuming Python 3.7 (ordered dicts) and the length of the adjustments match the length of the items in the dictionary, you can zip them together as follows:
for name, adjustment_amount in zip(roster, grade_adjustment):
roster[name] += adjustment_amount
>>> roster
{'ann': 80, 'bob': 75}
1 Comment
This is making several assumptions:
- the dictionary and the list have the same length (your final code should make sure they do)
- you are using a version of python in which the order of the dictionary keys is preserved (if not, you can make
grade_adjustmenta dictionary as well, as mentioned by other comments)
result = roster.copy()
for index, key in enumerate(roster):
result[key] += grade_adjustment[index]
1 Comment
You can use
def adjust_grades(roster, grade_adjustment):
for k, v in enumerate(grade_adjustment):
roster[list(roster.keys())[k]] = roster[list(roster.keys())[k]] + v
return roster
This gives output as you said {'ann': 80, 'bob': 75}
1 Comment
assuming 3.7 or ordered dict and equal length:
def adjust_grades(roster, grade_adjustment):
return {key:value + adjustment for (key, value), adjustment in
zip(roster.items(), grade_adjustment)}
print(adjust_grades({'ann': 75, 'bob': 80}, [5, -5]))
OrderedDict. Or define yourgrade_adjustmentas a dictionary:{'ann' : 5, 'bob' : -5 }grade_adjustmentshould also be a dictionary. Then,for name, adj in grade_adjustment.items(): roster[name] += adj