Remove value from dictionary element in list

Question:

I have two list of dictionaries, namely

bandits = [{'health': 15, 'damage': 2, 'id': 0}, {'health': 10, 'damage': 2, 'id': 0}, {'health': 12, 'damage': 2, 'id': 0}]
hero = [{'name': "Arthur", 'health': 50, 'damage': 5, 'id': 0}]

What I would like to do, is simulate a hero strike on each member of the bandits list, which consist in substracting the damage value of hero to the health value of each bandits entry. As an illustration, with the values given above, after the hero has dealt its blow, the bandits list should read

bandits = [{'health': 10, 'damage': 2, 'id': 0}, {'health': 5, 'damage': 2, 'id': 0}, {'health': 7, 'damage': 2, 'id': 0}]

I have tried several things, amongst which

for i, v in enumerate(bandits):
    bandits[i] = {k: (bandits[i][k] - hero[0].get('damage')) for k in bandits[i] if k=='health'}

which yields

bandits = [{'health': 10}, {'health': 5}, {'health': 7}]

i.e. the results for the health are good, but all other key:val pairs in the dictionaries contained in the bandits list are deleted. How can I correct my code?

Asked By: aheuchamps

||

Answers:

Don’t create new dictionaries, just subtract from the values in the existing dictionaries.

for bandit in bandits:
    bandit['health'] -= hero[0]['damage']
Answered By: Barmar

Depended on the goals/use case you can iterate the collection and update the value in-place (variable names are used from the "I have tried several things" code):

bandit = [{'health': 15, 'damage': 2, 'id': 0}, {'health': 10, 'damage': 2, 'id': 0}, {'health': 12, 'damage': 2, 'id': 0}]
knight_data = [{'name': "Arthur", 'health': 50, 'damage': 5, 'id': 0}]

for b in bandit:
    for k in knight_data:
        b['health'] -= k['damage']

Or:

for b in bandit:
    b['health'] -= knight_data[0]['damage']
Answered By: Guru Stron
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.