Adding an item to a dictionary in python?

I'm relatively new here, so please tell me if there is anything I should know, or any mistakes that I make wisely!

I am trying to add things to the dictionary through random selection, but my code does not seem to work!

File: sports.txt

Soccer, Joshua Lacrosse, Naome Lee Soccer, Kat Valentine Basketball, Huong Tennis, Sunny Basketball, Freddie Lacer 

my code is:

 def sportFileOpen(): sportFile = open("sport.txt") readfile = sportFile.readlines() sportFile.close() return(readfile) def sportCreateDict(sportFile): sportDict = {} for lines in sportFile: (sport, name) = lines.split(",") if sport in sportDict: sportDict[sport].append(name.strip()) else: sportDict[sport] = [name.strip()] return(sportDict) def sportRandomPick(name, sport, sportDict): if sport in sportDict: ransport = random.choice(sportDict.keys()) sportDict[ransport].append(name) print(name, "has been sorted into", ransport) def main(): sportFile = sportFileOpen() sportDict = sportCreateDict(sportFile) name = input("Enter the name: ") preferredSport = input("Which sport do they want? ") sportRandomPick(name, preferredSport, sportDict) main() 

I am trying to allow the user to enter their name and preferred sport group, and any sport that they prefer will have a higher chance of being randomly selected, then others (for example, if Jason chooses football, his chances of getting into football may double).

I don’t expect anyone to write me the code, I know that it takes a lot of time, and you have everything you need to do! But can someone explain to me how I will do this? I understand how to make random choices, but I don’t know how I would “double” the chances.

Also, I keep getting this error when running my code: NameError: global name 'random' is not defined

I thought I was doing this role right, but now I'm stuck. Can someone give their two cents for this?

+6
source share
2 answers

Try the following:

 def sportRandomPick(name, sport, sportDict): if sport in sportDict: ransport = random.choice(list(sportDict.keys()) + [sport]) # list of sports will contain preferred sport twice. sportDict[ransport].append(name) print(name, "has been sorted into", ransport) 

This will increase the chances of choosing your favorite sport by 2.

And don't forget import random

+1
source

I assume you are trying to use random.choice from python random.choice

you need to make sure it is imported at the top of the file:


import random

 def sportRandomPick(name, sport, sportDict): if sport in sportDict: ransport = random.choice(sportDict.keys()) sportDict[ransport].append(name) print(name, "has been sorted into", ransport) 
0
source

Source: https://habr.com/ru/post/1012606/


All Articles