如何为字典中的键分配多个值

How to assign multiple values to key in dictionary

我想为团队分配多个值,在字典中为用户输入的每个团队输赢。

def cricket_teams():
        no_of_teams=int(input("Please enter the number of the teams: "))
        
        main_dic={}
        for i in range(0,no_of_teams):
            
            main_dic["Team"]=[]
            main_dic["won"]=[]
            main_dic["lose"]=[] 
            name=str(input("Please enter the name of team: "))
            won_=int(input("How many time this team won a match: "))
            lose_=int(input("How many times this lose a match: "))
            main_dic["Name"].append(name)
            main_dic["won"].append(won_)
            main_dic["lose"].append(lose_)
    
    
        print(main_dic)
    
    
    cricket_teams()

但是当我 运行 上面的代码时,我得到如下输出:

{'Name': ['Sri lanka'], 'won': [1], 'lose': [2]}

我只得到最新组的结果。我应该如何为键分配多个值?

如果有两个团队,预期输出应该是:

{'Name': ['Sri lanka,Australia '], 'won': [1,2], 'lose': [2,2]}

您在 for 循环的每次迭代中都重新初始化了空的键值对。键应该在 for 循环之外创建一次

像这样,

def cricket_teams():
    no_of_teams = int(input("Please enter the number of the teams: "))

    main_dic = {}
    main_dic["Team"] = []
    main_dic["won"] = []
    main_dic["lose"] = []
    for i in range(0, no_of_teams):
        name = str(input("Please enter the name of team: "))
        won_ = int(input("How many time this team won a match: "))
        lose_ = int(input("How many times this lose a match: "))
        main_dic["Team"].append(name)
        main_dic["won"].append(won_)
        main_dic["lose"].append(lose_)

    print(main_dic)


cricket_teams()