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...
In Python I have a code: here's my problem, and below it is my code. Below...
In Python I have a code: here's my problem, and below it is my code. Below that is the error I received. Please assist. Complete the swapCaps() function to change all lowercase letters in string to uppercase letters and all uppercase letters to lowercase letters. Anything else remains the same. Examples: swapCaps( 'Hope you are all enjoying October' ) returns 'hOPE YOU ARE ALL ENJOYING oCTOBER' swapCaps( 'i hope my caps lock does not get stuck on' ) returns 'I...
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...
For Python, I cannot figure out why "and" is printing at the beginning of my list....
For Python, I cannot figure out why "and" is printing at the beginning of my list. Can someone help? listToPrint = [] while True: newWord = input("Enter a word to add to the list (prest return to stop adding words) > ") newWord == "": break else: listToPrint.append(newWord) for item in listToPrint[:-1]: print(item, end=', ') print('and', listToPrint[-1]) If I enter m, n, b to the list, it executes to and m, n, b
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,...
Python I am creating a class in python. Here is my code below: import csv import...
Python I am creating a class in python. Here is my code below: import csv import json population = list() with open('PopChange.csv', 'r') as p: reader = csv.reader(p) next(reader) for line in reader: population.append(obj.POP(line)) population.append(obj.POP(line)) class POP: """ Extract the data """ def __init__(self, line): self.data = line # get elements self.id = self.data[0].strip() self.geography = self.data[1].strip() self.targetGeoId = self.data[2].strip() self.targetGeoId2 = self.data[3].strip() self.popApr1 = self.data[4].strip() self.popJul1 = self.data[5].strip() self.changePop = self.data[6].strip() The problem is, I get an error saying:  ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT