Home > front end >  How do i complete maths and variable assignment inside a dictionary in python?
How do i complete maths and variable assignment inside a dictionary in python?

Time:02-01

Player1 = {
    "name":"Bob",
    "attack":7,
    "defence":5,
    "total":Player1["attack"] Player1["defence"],
}

How do I set total in the dictionary to be attack defense?

CodePudding user response:

Unfortunately what you're asking isn't do able as far as I'm aware... you'd be better using a class

like this:

class Player:

    def __init__(self):
        self.name = "Bob"
        self.attack = 7
        self.defence = 5
        self.total = self.attack   self.defence

player = Player()
print(player.total)

What you've got to remember is you've not instantiated the dict when you declare it, so inside the {} you can't call Player1 as it doesn't exist in the context yet.

By using classes you could also reuse the example above by doing something like:

class Player:

    def __init__(self, name, attack, defence):
        self.name = name
        self.attack = attack
        self.defence = defence
        self.total = self.attack   self.defence

player1 = Player(name="bob", attack=7, defence=5)
player2 = Player(name="bill", attack=10, defence=7)
print(player1.total)
print(player2.total)

EDIT: fixed typo

CodePudding user response:

You are currently trying to access Player1 before creating it.

You could do:

Player1 = {
    "name":"Bob",
    "attack":7,
    "defence":5
}
Player1["total"] = Player1["attack"]   Player1["defence"]

However, this is not ideal, because you need to remember to adjust the 'total' field whenever 'attack' or 'defence' change. It's better to compute the total value on the fly, since it is not an expensive computation.

This can be achieved by writing a Player class with a property total.

class Player:
    def __init__(self, name, attack, defence):
        self.name = name
        self.attack = attack
        self.defence = defence

    @property
    def total(self):
        return self.attack   self.defence

Demo:

>>> Player1 = Player('Bob', 1, 2)
>>> Player1.name, Player1.attack, Player1.defence, Player1.total
('Bob', 1, 2, 3)

CodePudding user response:

Let's say you don't want to compute value of the key total yourself. You can initialize it to None (Standard practice. Better than omitting it).

Player1 = {
    "name":"Bob",
    "attack":7,
    "defence":5,
    "total":None
}

Then update it's value later on.

Player1["total"] = Player1["attack"]   Player1["defence"]
  •  Tags:  
  • Related