Skip to content
Advertisement

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:

{'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:

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

Advertisement

Answer

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()
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement