user15103706
user15103706

Reputation:

how to modify a list value in a dictionary in place?

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

Upvotes: 0

Views: 60

Answers (4)

Dani Mesejo
Dani Mesejo

Reputation: 61910

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]}

Upvotes: 1

balderman
balderman

Reputation: 23815

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]}

Upvotes: 0

user2390182
user2390182

Reputation: 73450

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.

Upvotes: 0

Tom Ron
Tom Ron

Reputation: 6181

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()}

Upvotes: 0

Related Questions