How to assign value to variable in list [PYTHON]

Question:

How can I do something like this on python :

class Game:
    
    def __init__(self, size: int):
        self.settings = { 
            'timeout_turn' = 0
            'timeout_match' = 0
            'max_memory' = 0
            'time_left' = 2147483647
            'game_type' = 0
            'rule' = 0
            'evaluate' = 0
            'folder' = './'
            }

there is an error, I think this is not the right way to do it but I didn’t find an other solution.

Thanks in advance

Asked By: Lewisuehjo

||

Answers:

To make it work you need to replace the = by and : and add a , after every entry.

class Game:
    def __init__(self, size: int):
        self.settings = { 
            'timeout_turn': 0,
            'timeout_match': 0,
            'max_memory': 0,
            'time_left': 2147483647,
            'game_type': 0,
            'rule': 0,
            'evaluate': 0,
            'folder': './'
        }

By doing this you are creating a class variable named settings that is of type dictionary. Dictionaries are also known as maps in other languages. They use immutable values as indexes (keys) instead of numbers like in lists.

Answered By: Bas van der Linden

here you go but it’s a dictionnary not a list

class Game:
    def __init__(self, size: int):
    self.settings = { 
        'timeout_turn' : 0,
        'timeout_match' : 0,
        'max_memory' : 0,
        'time_left' : 2147483647,
        'game_type' : 0,
        'rule' : 0,
        'evaluate' : 0,
        'folder' : './',
        }
Answered By: Ghassen Sultana

If you want your settings data to be a dictionnary : instead of = to affect value to the key (variable name).

If you just want to create new variables you could do it like that :

class Game:

def __init__(self, size: int):
    self.timeout_turn=0
    self.max_memory=0
    ....
        
    
Answered By: Kupofty

Hi I Hope you are doing well!

Because you are using dict the syntax should have : instead of =:

class Game:

    def __init__(self, size: int) -> None:
        """Initialize."""

        self.settings = {
            "timeout_turn": 0,
            "timeout_match": 0,
            "max_memory": 0,
            "time_left": 2147483647,
            "game_type": 0,
            "rule": 0,
            "evaluate": 0,
            "folder": "./",
        }

or if you want to have it as attributes you can do this:

class Game:

    def __init__(self, size: int) -> None:
        """Initialize."""

        self.timeout_turn = 0
        self.timeout_match = 0

        ...
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.