Home > Blockchain >  How to add values from first dict to values in second dict
How to add values from first dict to values in second dict

Time:05-26

I stuck, and need little help.

How can I add values if i have a dict with other dictionaries?

For example:

player_equipment = {'Boots:': [('Defence', 4), ('Mana', 13), ('Stamina', 30)], 'Gloves:': [('Attack', 5), ('Defence', 1), ('Health', 19), ('Mana', 3), ('Stamina', 29)]}

I need a result:

player_equipment_statictic = {'Attack':5, 'Defence':5,'Health':19 'Mana':16, 'Stamina':59}  

In next my step i will try add player_equipment_statictic to player_stats where the player will have his statistic in class Player:

class Player:
    def __init__(self, health=100, max_health=1300, mana=100, stamina=222, attack=10, defence=1, magic=11, lucky=1, level=1, experience=95, points=1):
        self.health = health
        self.max_health = max_health
        self.mana = mana
        self.stamina = stamina
        self.defence = defence
        self.attack = attack
        self.magic = magic
        self.lucky = slucky
        self.level = level
        self.experience = experience
        self.points = points

CodePudding user response:

player_equipment = {'Boots:': [('Defence', 4), ('Mana', 13), ('Stamina', 30)],
                    'Gloves:': [('Attack', 5), ('Defence', 1), ('Health', 19), ('Mana', 3), ('Stamina', 29)]}
player_equipment_statictic = {}

# iterating through player_equipment extracting item list
for _, item_list in player_equipment.items():
    # iterating through item_list extracting pairs of item and count
    for item, count in item_list:
        # checking if item exists in new dictionary
        if item in player_equipment_statictic:
            # updating item in the new dictionary
            player_equipment_statictic[item]  = count
        # if item not exists in the new dictionary
        else:
            # creating new item in the new dictionary with the count as value
            player_equipment_statictic[item] = count

print(player_equipment_statictic)

output

{'Defence': 5, 'Mana': 16, 'Stamina': 59, 'Attack': 5, 'Health': 19}
  • Related