Adding sum of value back to Dictionary

Question:

I have a dictionary, and I’m trying to add 100 to the values. I’m able to do so, but I can’t seem to figure out how to insert the new values to show up in the dictionary.

for value in artist_dict.values():
  value += 100
  
print(artist_dict)

I tried .append(value) and received an error message. Also, value = artist_dict.values(), artist_dict.update(value), artist_dict.values() = value, and artist_dict.updated(value +=100) all received an error message.

Asked By: Coder94

||

Answers:

You need to set the value in the dict via the key. What you’re doing is overriding only the loop variable named value

for key in artist_dict.keys():
  artist_dict[key] += 100

.keys() isn’t strictly necessary since that is the default iteration element returned.

Answered By: OneCricketeer

you can add a fixed value to every value in a dictionary by iterating over the dictionary and adding the fixed value to each value. Here’s an example:

my_dict = {'a': 10, 'b': 20, 'c': 30}

fixed_value = 5

for key in my_dict:
    my_dict[key] += fixed_value

print(my_dict)

In this example, my_dict contains the original dictionary with keys ‘a’, ‘b’, and ‘c’, and corresponding values 10, 20, and 30, respectively. The fixed_value variable is set to the value that you want to add to each value in the dictionary.

The for loop iterates over the keys in the dictionary, and the my_dict[key] += fixed_value statement adds the fixed value to the current value for that key. This statement is equivalent to my_dict[key] = my_dict[key] + fixed_value.

Finally, the updated dictionary is printed using the print() function.

Answered By: Mohit Shukla
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.