Typhoon2 Typhoon2 - 1 year ago 149
Python Question

Adding element to a dictionary in python?

I'm relatively new here, so please tell me if there is anything I should know or any mistakes I am making manner wise!

I am trying to add things onto a dictionary through random choice, but my code doesn't seem to work!

The file:

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

my code so far:

def sportFileOpen():

sportFile = open("sport.txt")
readfile = sportFile.readlines()

def sportCreateDict(sportFile):

sportDict = {}

for lines in sportFile:
(sport, name) = lines.split(",")

if sport in sportDict:

sportDict[sport] = [name.strip()]


def sportRandomPick(name, sport, sportDict):

if sport in sportDict:

ransport = random.choice(sportDict.keys())


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)


I am trying to allow a user to input their name and preferred group of sport, and whatever sport they prefer will have a higher chance of being randomly picked then the others (for example if Jason chooses soccer his chances of getting in soccer may double).

I don't expect anyone to write code for me, I know it's time consuming and you have better things to do! But can anyone maybe explain to me how I would go about doing 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 that part right but now i'm stuck. Can anyone give their two cents on this?

Answer Source

Try this:

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


        print(name, "has been sorted into", ransport)

This will increase chances of preferred sport to be picked by 2.

And don't forget to import random

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download