Python Forum
Dictionary help please!
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary help please!
#1
Hello, I have been working on trying to find the cause to my issue for a couple hours now, and cant seem to dig up anything to help. I'm sure I am just over complicating things as I usually do, so any guidance would be very much appreciated.

The dictionary that I am trying to create is called roster, and it is all in a class called RosterClass. I thought I was doing it right but seems like I may be wrong.
The actual error and my code is below.

This is the Error I keep running into:

Traceback (most recent call last):
File "D:/Programing/PhyCharm Projects/Week 5.3.py", line 2, in <module>
class RosterClass:
File "D:/Programing/PhyCharm Projects/Week 5.3.py", line 112, in RosterClass
roster = addPlayer(roster)
File "D:/Programing/PhyCharm Projects/Week 5.3.py", line 74, in addPlayer
roster[newName] = roster(newName, newplayerNumber, newphoneNumber)
TypeError: 'dict' object is not callable


# Roster class definition
class RosterClass:
    name = ""
    playerNumber = 0
    phoneNumber = 0

    def notFound(self):
        print('\033[1m{:10s}\033[0m'.format("Im sorry, That name was not found"))

    def space(self):
        print("")
        print("")

    def __init__(self, name, playerNumber, phoneNumber):
        self.name = name
        self.playerNumber = playerNumber
        self.phoneNumber = phoneNumber

#mutator methods
    def setname(self,name):
        self.name = name

    def setplayerNumber(self, playerNumber):
        self.playerNumber = playerNumber

    def setphoneNumber(self, phoneNumber):
        self.phoneNumber = phoneNumber

#accessor methods
    def getname(self):
        return self.name

    def getplayerNumber(self):
        return self.playerNumber

    def getphoneNumber(self):
        return self.phoneNumber

    def displayData(self):
        self.space()
        print("===========Team Roster============")
        self.space()
        print("Player's name:", self.name)
        print("Player's jersey number:", self.playerNumber)
        print("Player's phone number:", self.phoneNumber)

#programming functions and import data
    def menu(space):
        space('self')
        print("1. Display Team Roster.")
        print("2. Add Member.")
        print("3. Remove Member.")
        print("4. Edit Member.")
        print("9. Exit Program.")
        space('self')
        return int(input("Selection:"))

    def printRoster(roster):
        if len(roster) == 0:
            print("The roster is currently empty.")
        else:
            for x in roster.keys():
                roster[x].displayData()

    def addPlayer(roster):
        newName = input("Enter new player's name:")
        newplayerNumber = input("Enter the player's jersey number:")
        newphoneNumber = input("Enter player's phone number:")
        roster[newName] = roster(newName, newplayerNumber, newphoneNumber)
        return roster

    def removePlayer(roster):
        removeName = input("Enter player's name to be removed:")
        if removeName in roster:
            del roster[removeName]
        else:
            notFound('self')
        return roster

    def editPlayer(roster):
        oldName = input("What name would you like to change?")
        if oldName in roster:
            newName = ("Enter the player's new name:")
            newplayerNumber = ("Enter the player's new jersey number:")
            newphoneNumber = ("Enter the player's new phone number:")
            roster[oldName] = RosterClass(newName, newplayerNumber, newphoneNumber)
            print("The new name is,", new_name)
            space()
        else:
            notFound()
            space()
        return roster

    # Start of program.
    space('self')
    # Figured out how to change font color to make program a little more appealing.
    print('\033[1m{:10s}\033[0m'.format("\033[34;48m Welcome to Raven's Team Manager\n"))
    space('self')

    roster = {}
    menuSelection = menu(space)

    while menuSelection != 9:
        if menuSelection == 1:
            printRoster(roster)
        elif menuSelection == 2:
            roster = addPlayer(roster)
        elif menuSelection == 3:
            roster = removePlayer(roster)
        elif menuSelection == 4:
            roster = editPlayer(roster)

    print("Thank you for choosing Raven's Team Manager, Good Bye!")
Reply
#2
There's a couple things in here that don't make sense, but let's start with the error you're getting:
Error:
File "D:/Programing/PhyCharm Projects/Week 5.3.py", line 74, in addPlayer roster[newName] = roster(newName, newplayerNumber, newphoneNumber) TypeError: 'dict' object is not callable
A dict isn't callable.  roster is a dict.  So roster(newName, newplayerNumber, newphoneNumber) doesn't make sense.  What are you trying to do here?

Next, you have a class, but it looks like a lot of the methods of that class are expecting to be passed something that they won't.  The first argument to every method is always a reference to the current instance, which is named self by convention.  So def printRoster(roster): doesn't make sense, since roster would never be the first argument to that function.  But then again, it doesn't really look like you need an object at all for this... is there a reason you defined a class?
Reply
#3
Thank you for the reply Nilamo, This is for an entry college level course and my prof. asked us to include a class, as that and dictionaries is what we had "learned" about.

Basically I am trying to build onto an already completed code, adding a dictionary to store a players name their jersey number and a phone number. I had tried using self instead of roster but that didnt work either. Im sure im just over complicating things and getting confused because ive been combing through the internet for hours looking for answers.

Here are the directions if that might help:

Your program for keeping track of team members is coming along, but now you want to be able to include phone numbers and jersey numbers along with your team member’s name. Modify your program from week 4 so that the program utilizes object-oriented programming to create a member object which can accept the player’s name, phone number, and jersey number. You will need to replace the list with a dictionary to help in locating objects for removal and editing. Again, File Access for long-term storage is not required for this assignment.

For this project:

You will submit your python code in either the original .py file, or copied into a .txt file.
A screenshot of your code having been executed (run). How to Take a Screenshot
Tips: While dictionaries resemble lists, remember that they are not the same! It is better to use FOR loops, not WHILE loops with index values.

Your class structure does not need a full set of accessor and mutator methods getName(), setName(newName), however it they will be helpful in the next week.

(Oct-02-2017, 07:34 PM)nilamo Wrote: There's a couple things in here that don't make sense, but let's start with the error you're getting:
Error:
File "D:/Programing/PhyCharm Projects/Week 5.3.py", line 74, in addPlayer roster[newName] = roster(newName, newplayerNumber, newphoneNumber) TypeError: 'dict' object is not callable
A dict isn't callable.  roster is a dict.  So roster(newName, newplayerNumber, newphoneNumber) doesn't make sense.  What are you trying to do here?

Next, you have a class, but it looks like a lot of the methods of that class are expecting to be passed something that they won't.  The first argument to every method is always a reference to the current instance, which is named self by convention.  So def printRoster(roster): doesn't make sense, since roster would never be the first argument to that function.  But then again, it doesn't really look like you need an object at all for this... is there a reason you defined a class?
Reply
#4
Is RosterClass supposed to represent a roster of multiple people, or a single person in the roster?

How you answer that determines how you can fix the error, as right now you're treating it as both at the same time (for example, a collection of people means it wouldn't make sense for it to have a getname, but if it's just one, then it doesn't make sense to have an editPlayer).
Reply
#5
It would be for multiple people. I need the roster to be editable. So that I can remove someone, add someone, edit someone, and then print a full list of whomever I had added to the roster.
(Oct-02-2017, 08:32 PM)nilamo Wrote: Is RosterClass supposed to represent a roster of multiple people, or a single person in the roster?

How you answer that determines how you can fix the error, as right now you're treating it as both at the same time (for example, a collection of people means it wouldn't make sense for it to have a getname, but if it's just one, then it doesn't make sense to have an editPlayer).

This is the example of using dictionaries and objects together that was given to my class, and what I was trying to use as a guide to incorporate a dictionary and object into my code.
#Pet class definition

class petClass:

    name = ""

    type = ""

    owner=""

    age = 0

    def __init__(self, name, age, type, owner):

 

        self.name = name

 

        self.age = age

 

        self.type = type

 

        self.owner = owner

 

 

#mutator methods

 

    def setname(self, name):

 

        self.name = name

 

    def setage(self, age):

 

        self.age = age

 

    def settype(self, type):

 

        self.type = type

 

    def setowner(self, owner):

 

        self.owner = owner

 

    def setNewOwner(self, owner):

 

        self.setowner(owner)

 

 

#accessor methods

 

    def getname(self):

 

        return self.name

 

    def getage(self):

 

        return self.age

 

    def gettype(self):

 

        return self.type

 

    def getowner(self):

 

        return self.owner

 

    def displayData(self):

 

        print("")

 

        print("Pet information: ")

 

        print("------------------------")

 

        print("Name:", self.name)

 

        print("Age:", self.age)

 

        print("Type:", self.type)

 

        print("Owner:", self.owner)

 

 

#program functions and import data

 

 

def displayMenu():

 

    print("===========Main Menu===========")

 

    print("1. Display pets.")

 

    print("2. Add pet.")

 

    print("3. Remove pet.")

 

    print("4. Edit pet.")

 

    print("9. Exit Program.")

 

    print("")

 

    return int(input("Selection> "))

 

def printPets(pets):

 

    if len(pets) == 0:

 

        print("No current pets in memory.")

 

    else:

 

        for x in pets.keys():

 

            pets[x].displayData()

 

def addPet(pets):

 

    newName = input("Enter new pet's name: ")

 

    newAge = int(input("Pet's age: "))

 

    newType = input("Pet type: ")

 

    newOwner = input("Pet's owner: ")

 

#notice, we used the pet's name as both the element's name as

 

#well as the actual pet's name. Keep that in mind as the element's

 

#name is how we will refer to the correct pet.

 

    pets[newName] = petClass(newName, newAge, newType, newOwner)

 

#Return updated list.

 

    return pets

 

def removePet(pets):

 

    removeName = input("enter pet's name to be removed: ")

 

#check first to see if the given name exists in the list.

 

    if removeName in pets:

 

#use the del keyword to delete the entry at the given name.

 

        del pets[removeName]

 

    else:

 

        print("Pet not found in list.")

 

#Return updated list.

 

    return pets

 

 

def editPet(pets):

 

#get the name of the member to be changed.

 

    oldName = input("Enter the name of the Pet you want to edit: ")

 

#see if name exists in list, if so, get index of given name, accept new

 

#name, and replace the name in the list with the new name.

 

#Return updated list.

 

    if oldName in pets:

 

        newName = input("Enter the pet's new name: ")

 

        newAge = int(input("Pet's new age: "))

 

        newType = input("Pet's new type: ")

 

        newOwner = input("Pet's new owner: ")

 

        pets[oldName] = petClass(newName, newAge, newType, newOwner)

 

    else:

 

        print("No such pet in memory")

 

#Return updated list.

 

    return pets

 

#Beginngin of program code

 

print("Welcome to the Team Manager")

 

pets = {}

 

menuSelection = displayMenu()

 

 

#The main program loop will detect the correct entry and call the

 

#appropriate method per the user's selection.

 

while menuSelection != 9:

 

    if menuSelection == 1:

 

        printPets(pets)

 

    elif menuSelection == 2:

 

        pets = addPet(pets)

 

    elif menuSelection == 3:

 

        pets = removePet(pets)

 

    elif menuSelection == 4:

 

        pets = editPet(pets)

 

    menuSelection = displayMenu()

 

print ("Exiting Program...")

Still in regards to the dictionary issues im having. I excluded the class and went to the basic program I started with, which gets rid of a lot of crap. I finally have information saving to a dictionary. Is there a way to split values pertaining to a key in said dictionary?
For instance I want my output to look like

Name: Kyle
Jersey number: 12
Phone number: xxx-xxx-xxxx

but instead it is showing up as

Name: Kyle, Jersey number: (12, 'xxx-xxx-xxxx') Phone number:(12, 'xxx-xxx-xxxx')

Here is the code for this (It is excluding a lot of what is being asked in the assignment I believe but its getting the job done"ish":
#Team manager
global selection  # globalizing selection so that other functions are able to read it.
selection=0
teamRoster = {}  # creating a dictionary to store roster entries in.
# creating my list of modules to use within my program.
def notFound():
    print('\033[1m{:10s}\033[0m'.format("Im sorry, That name was not found"))
def line():
    print('\033[1m{:10s}\033[0m'.format("-------------------------------------------"))
def space():
    print()
    print()
def menu():
    line()
    print("1. Display Team Roster.")
    print("2. Add Member.")
    print("3. Remove Member.")
    print("4. Edit Member.")
    print("9. Exit Program.")
    global selection    # again making sure that the input for selection is global.
    selection = int(input("Please make a selection:"))
    line()
    space()
def printRoster():
    for x in teamRoster.keys():
        print("Name:", x, ", Jersey number:", teamRoster[x], "Phone number:", teamRoster[x])
    else:
        print("Roster is Empty.")
        space()
def addMember():
    name = input("Type in players name to be added to the roster:")
    number= int(input("Type in the player's jersey number:"))
    phone= input("Type in the player's phone number:")
    print(name, "has been added to the roster.")
    teamRoster[name] = number, phone
    space()
def removeMember():
    name = input("Who would you like to remove from the roster?")
    if name in teamRoster:
        del teamRoster[name]
        print(name, " has been removed from the roster.")
        space()
    else:
        notFound()
        space()
def editMember():
    name = input("What name would you like to change?")
    if name in teamRoster:
        del teamRoster[name]
        new_name = input("What is the new name?")
        number = int(input("What is the new jersey number?"))
        phone = input("What is the new phone number?")
        teamRoster[new_name] = number, phone
        print("The new name is,", new_name)
        space()
    else:
        notFound()
        space()
# Start of program.
space()
# Figured out how to change font color to make program a little more appealing.
print('\033[1m{:10s}\033[0m'.format("\033[34;48m Welcome to Raven's Team Manager\n"))
space()
while selection !=9:    # Starting while loop.
    menu()
# start of menu selections with the modules as the outcome to the selection.
    if selection == 1:
        printRoster()
    elif selection == 2:
        addMember()
    elif selection == 3:
       removeMember()
    elif selection == 4:
        editMember()
print("Thank you for choosing Raven's Team Manager, Good Bye!")
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020