Reputation: 53
Let's say I had these two dictionaries, both containing similar keys to each other:
d_1 = {'a': 3, 'b': 4, 'c': 1}
d_2 = {'a': 5, 'b': 6, 'c': 9, 'd': 7}
Now, let's say I want to take the values of d_1
and add them to the corresponding values of d_2
. How would I add the values of d_1
's a
key to the respective key in d_2
w/o individually saying d_2['a'] += d_1['a']
for each key? How could I go about writing a function that can take two dicts, compare their keys, and add those values to the identical existing key values in another dict?
For example, if I had a class named player
and it has an attribute of skills
which contains several skills and their values, e.g. strength: 10
or defense: 8
, etc. Now, if that player
were to come across an armor set, or whatever, that buffed specific skills, how could I take that buff dictionary, see what keys it has in common with the player
's skills
attribute, and add the respective values?
Upvotes: 1
Views: 603
Reputation: 41
For every key in d_2, check if them in d_1, if so, add them up.
for key in d_2:
if key in d_1:
d_2[key] += d_1[key]
It seems you want to built a game, then you might not want to mess with the player's attribute. add them up and put the outcome to a new dict would be better. What's more, you can add more than two dict together, as you might have more than one buff.
for key in player:
outcome[key] = 0
for buff in buffs:
if key in buff:
outcome[key] += buff[key]
outcome[key] += player[key]
Upvotes: 3