Home > Blockchain >  how to modify a list value in a dictionary in place?
how to modify a list value in a dictionary in place?

Time:10-12

I have a dictionary that has lists as its value:

scores = {'Anna': [127, 150, 168], 'Jamie': [188, 176, 190]}

How can I multiply each value in the list by 0.5 without creating a new dictionary or a new list?

Output:

scores = {'Anna': [63.5, 75, 84], 'Jamie': [94, 88, 95]}

I have tried:

for num in scores.values():
        for x in num:
            x *= 0.5
return x

CodePudding user response:

Iterate over the items and update in-place using enumerate:

scores = {'Anna': [127, 150, 168], 'Jamie': [188, 176, 190]}


for key, values in scores.items():
    for i, value in enumerate(values):
        values[i] = value * 0.5

print(scores)

Output

{'Anna': [63.5, 75.0, 84.0], 'Jamie': [94.0, 88.0, 95.0]}

CodePudding user response:

You can use a combination of dict comprehension and list comprehension -

frac = 0.5
scores2 = {k: [frac*score for score in v] for k, v in scores.items()}

CodePudding user response:

You can use slice assignment on the value lists directly which is a mutation and does not require any rebinding (or other involvement) of the keys:

for nums in scores.values():
    nums[:] = [x * 0.5 for x in nums]
    # or if you like it cryptic:
    # nums[:] = map(.5.__mul__, nums)

Note that

x *= 0.5

is just a reassignment of the loop variable and not reflected in the list.

CodePudding user response:

How can I multiply each value in the list by 0.5 without creating a new dictionary or a new list?

Like the below

scores = {'Anna': [127, 150, 168], 'Jamie': [188, 176, 190]}
for values in scores.values():
  for idx in range(0,len(values)):
    values[idx] = values[idx] * 0.5
print(scores)

output

{'Anna': [63.5, 75.0, 84.0], 'Jamie': [94.0, 88.0, 95.0]}
  • Related