[Solved] Check and update dictionary if key exists doesn’t change value


To give some example of what we mean, I think this is kind of alright

import random
import pickle

class BaseCharacter:

    def __init__(self):
        self.gold = random.randint(25, 215) * 2.5
        self.currentHealth = 100
        self.maxHealth = 100
        self.stamina = 10
        self.resil = 2
        self.armor = 20
        self.strength = 15
        self.agility = 10
        self.criticalChance = 25
        self.spellPower = 15
        self.speed = 5
        # set gold as random gold determined from before
        self.first_name="New"
        self.last_name="Player"
        self.class_ = None

    def update(self, attrs, factors):
        # Maybe a try except would be nice here
        for attr, fac in zip(attrs, factors):
            val = getattr(self, attr)
            setattr(self, attr, val * fac)

    def show_stats(self):
        for attr in self.__dict__:  # Don't do this... but meh
            print(attr, getattr(self, attr))

    def save(self):
        with open(self.first_name+'_'+self.last_name, 'wb') as f:
            pickle.dump(self, f)

    @staticmethod
    def load(filename):
        with open(filename, 'rb') as f:
            return pickle.load(f)


class WarriorCharacter(BaseCharacter):

    def __init__(self, first_name, last_name):
        super().__init__()
        self.class_ = 'Warrior'
        self.first_name = first_name
        self.last_name = last_name
        self.update(['stamina', 'resil', 'armor'], [1.25, 1.25, 1.35])

w = WarriorCharacter('Jon', 'Snow')
w.show_stats()
w.save()
loadedW = WarriorCharacter.load('Jon_Snow')
print(loadedW.class_)

6

solved Check and update dictionary if key exists doesn’t change value