Question

In: Computer Science

(Python) This is my code for printing a roster for a team. When I print to...

(Python) This is my code for printing a roster for a team. When I print to the console, it makes the first player's name show up as number 2, and it says [] (its just blank for 1). How can I fix that so the first player's name is 1, not skipping 1 and going to 2.

def file_to_dictionary(rosterFile):

myDictionary={}

myDict=[]

  

with open(rosterFile,'r') as f:

for line in f:

  

(num,first,last,position)=line.split()

myDictionary[num]= myDict

myDict=[first, last, position]

print (myDictionary)

return myDictionary

  

file_to_dictionary((f"../data/playerRoster.txt"))

  

Solutions

Expert Solution

In this program I see that you are trying to read a file line by line and create a dicitionary out of the data in it. Also, i assume that the data in each line are seperated by spaces, and that is why you are using line.split().

With those assumptions in mind, I see a few logical error in your code.

First, you are opening the file in read mode, that part is correct. But, no where in the entire code, the data in the file is being read. the file pointer is f, use that to read the data, and split them across newlines. You will get a list of all the lines in the file. You can later use this list to access each line of the file.

Then,check the for loop. You cannot loop over a file pointer. Rather we will loop over the list we have created in the previous step.

Finally, don't assign myDict to myDictionary[num] and change it later. First change the myDict list and then assign it to myDictionary[num]. This is the reason why the first line of the file is not showing up in myDictionary.

modified program:

def file_to_dictionary(rosterFile):

myDictionary={}

with open(rosterFile,'r') as f:

data = f.read().split('\n')

for line in data:

(num,first,last,position)=line.split()

myDict=[first, last, position]

myDictionary[num]= myDict

print (myDictionary)

return myDictionary

file_to_dictionary((f"../data/playerRoster.txt"))

If your issue is still not fixed, please reach out to me in comments.


Related Solutions

c++ I have my code mostly finished but when printing it is printing incorrectly so 62345...
c++ I have my code mostly finished but when printing it is printing incorrectly so 62345 should == |0|0|0|0|0|0|0|0|6|2|3|4|5| but it is printing as == 5|4|3|2|6|0|0|0|0|0|0 is it with my bigint::bigint(const char c[]) or the output operator<< and with the output should i have something like a while loop to check for leading zeros and print them before any addition. ----------------------------------------------------------------------------------------------------------------------- bigint.hpp; #ifndef BIGINT_HPP #define BIGINT_HPP const int CAPACITY = 400; class bigint { public: bigint(); //default constructor bigint(int); bigint(const...
Python I want to name my hero and my alien in my code how do I...
Python I want to name my hero and my alien in my code how do I do that: Keep in mind I don't want to change my code except to give the hero and alien a name import random class Hero:     def __init__(self,ammo,health):         self.ammo=ammo         self.health=health     def blast(self):         print("The Hero blasts an Alien!")         if self.ammo>0:             self.ammo-=1             return True         else:             print("Oh no! Hero is out of ammo.")             return False     def...
Why does my code print nothing in cout? I think my class functions are incorrect but...
Why does my code print nothing in cout? I think my class functions are incorrect but I don't see why. bigint.h: #include <string> #include <vector> class BigInt { private:    int m_Input, m_Temp;    std::string m_String = "";    std::vector<int> m_BigInt; public:    BigInt(std::string s)   // convert string to BigInt    {        m_Input = std::stoi(s);        while (m_Input != 0)        {            m_Temp = m_Input % 10;            m_BigInt.push_back(m_Temp);       ...
This is my code for python. I am trying to do the fourth command in the...
This is my code for python. I am trying to do the fourth command in the menu which is to add an employee to directory with a new phone number. but I keep getting error saying , "TypeError: unsupported operand type(s) for +: 'dict' and 'dict". Below is my code. What am I doing wrong? from Lab_6.Employee import * def file_to_directory(File): myDirectory={}       with open(File,'r') as f: data=f.read().split('\n')    x=(len(data)) myDirectory = {} for line in range(0,199):      ...
Soccer team roster (Dictionaries) This program will store roster and rating information for a soccer team.
Soccer team roster (Dictionaries) This program will store roster and rating information for a soccer team. Coaches rate players during tryouts to ensure a balanced team. (1) Prompt the user to input five pairs of numbers: A player's jersey number (0 - 99) and the player's rating (1 - 9). Store the jersey numbers and the ratings in a dictionary. Output the dictionary's elements with the jersey numbers in ascending order (i.e., output the roster from smallest to largest jersey...
Program: Soccer team roster This program will store roster and rating information for a soccer team....
Program: Soccer team roster This program will store roster and rating information for a soccer team. Coaches rate players during tryouts to ensure a balanced team. (1) Prompt the user to input five pairs of numbers: A player's jersey number (0 - 99) and the player's rating (1 - 9). Store the jersey numbers in one int array and the ratings in another int array. Output these arrays (i.e., output the roster). (3 pts) Ex: Enter player 1's jersey number:...
hi i do not know what is wrong with my python code. this is the class:...
hi i do not know what is wrong with my python code. this is the class: class Cuboid: def __init__(self, width, length, height, colour): self.__width = width self.__length = length self.__height = height self.__colour = colour self.surface_area = (2 * (width * length) + 2 * (width * height) + 2 * (length * height)) self.volume = height * length * width def get_width(self): return self.__width def get_length(self): return self.__length def get_height(self): return self.__height def get_colour(self): return self.__colour def set_width(self,...
Working with Python. I am trying to make my code go through each subject in my...
Working with Python. I am trying to make my code go through each subject in my sample size and request something about it. For example, I have my code request from the user to input a sample size N. If I said sample size was 5 for example, I want the code to ask the user the following: "Enter age of subject 1" "Enter age of subject 2" "Enter age of subject 3" "Enter age of subject 4" "Enter age...
I have an unexpected indent with my python code. please find out whats wrong with my...
I have an unexpected indent with my python code. please find out whats wrong with my code and run it to show that it works here is the code : def main(): lis = inputData() customerType = convertAcct2String(lis[0]) bushCost = getBushCost(lis[0],int(lis[1],10)) flowerCost = getFlowerBedCost(int(lis[2],10),int(lis[3],10)) fertiCost = getFertilCost(int(lis[4],10)) totalCost = calculateBill(bushCost,fertiCost,flowerCost) printReciept(customerType,totalCost,bushCost,fertiCost,flowerCost) def inputData(): account, number_of_bushes,flower_bed_length,flower_bed_width,lawn_square_footage = input("Please enter values").split() return [account, number_of_bushes,flower_bed_length,flower_bed_width,lawn_square_footage] def convertAcct2String(accountType): if accountType== "P": return "Preferred" elif accountType == "R": return "Regular" elif accountType == "N": return...
Below is my source code for file merging. when i run the code my merged file...
Below is my source code for file merging. when i run the code my merged file is blank and it never shows merging complete prompt. i dont see any errors or why my code would be causing this. i saved both files with male names and female names in the same location my source code is in as a rtf #include #include #include using namespace std; int main() { ifstream inFile1; ifstream inFile2; ofstream outFile1; int mClientNumber, fClientNumber; string mClientName;...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT