简体   繁体   English

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

[英]How to assign multiple values to key in dictionary

I want to assign multiple values to Teams, lose and won in dictionary for every team entered by the user.我想为团队分配多个值,为用户输入的每个团队在字典中输赢。

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()

But when I run the code above I get output like:但是当我运行上面的代码时,我得到 output ,例如:

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

I only get the result of the latest team.我只得到最新团队的结果。 What should I do to assign multiple values to key?我应该怎么做才能为键分配多个值?

if there are two teams the expected output should be:如果有两个团队,预期的 output 应该是:

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

Like this,像这样,

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()

you are re-initialising empty key-value pairs in every iteration of your for loop.您在 for 循环的每次迭代中都重新初始化空键值对。 Keys should be created outside the for loop once键应该在 for 循环之外创建一次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM