I want to multiply scores inside the dictionary by an integer given in the parameter for a specific key. If the integer is not for the key then I want to return the scores as is.
def main():
scores ={'Bella': [2, 8, 3], 'Jack'= [8, 9, 7, 4]}
multiply_scores(scores, 'Bella', 3)
print(scores['Bella'])
print(scores['Jack'])
Expected output:
[6, 24, 9]
[8, 9, 7, 4]
My current output is:
[6, 24, 9]
[24, 27, 21, 12]
How can I fix my code to get the expected output:
def multiply_scores(scores, name, number):
for values in scores.values():
for index in range(0,len(values)):
values[index] = round((values[index] * number))
return values
CodePudding user response:
You've made this harder than it needs to be.
def multiply_scores(scores, name, number):
scores[name] = [i*number for i in scores[name]]
CodePudding user response:
Since the name is a key in the dictionary, use it to get the list. When you assign to a slice object, the list will iterate the thing on the right, which is a convenient way to do an in-place modification of the list.
def multiply_scores(scores, name, number):
lst= scores[name]
lst[:] = (v * number for v in lst)
def main():
scores ={'Bella': [2, 8, 3], 'Jack':[8, 9, 7, 4]}
multiply_scores(scores, 'Bella', 3)
print(scores['Bella'])
print(scores['Jack'])
main()
CodePudding user response:
I think you should get list from your dictionary and update that list. and before that check if the keys in the dictionary.
def multiply_scores(scores, name, number):
try:
scores[name] = [i * number for i in scores[name]]
return scores
except KeyError:
return scores
CodePudding user response:
Using list comprehension as Tim said is great (and arguably more efficient), but if you want simpler looking code that's closer to what you posted, you can see this:
Currently, your name
parameter does not do anything... you'd have to use it to check the name within the dictionary first before altering the values of the given name. I'd modify your function as this:
def multiply_scores(scores, name, number):
for key, values in scores.items():
if key == name:
for index in range(0,len(values)):
values[index] = round((values[index] * number))
return values