首页 > 解决方案 > How to add values to a dictionary of class in python

问题描述

It's my first time posting here. I'm currently facing a problem where my goal is for user to have a command where my dictionary of classes will add exp to the class argument. (I'm kinda bad at english if you want some clarification, Please let me know)

class Stats:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

stre = {1: Stats(name='Excercise', exp=0, description="This is a description"),
        2: Stats(name='Gym', exp=0, description="Gym description")}

def statsComm():
    command_list = ["stre", "inte", "will"]
    print("Select Command {}".format(command_list))
    command = input("> ")
    if command == 'stre':
        for key, value in stre.items():
            print(value.exp)


while True:
    print("Enter Command {}".format(command_list))
    command = input("> ")
    if command == 'stats':
        statsComm()

Currently it prints the right thing. But I don't know how to add value to exp of an individual class when they enter a command. Thank you :D

标签: pythonpython-3.x

解决方案


You can specify individual classes within the for loop as follows:

for key, value in stre.items():
    if value.name == 'Exercise': 
        value.exp += 1

推荐阅读