Question

In: Computer Science

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):

  

  

myDir=data[line].split(",")

firstName=myDir[0]

lastName=myDir[1]

title=myDir[2]

email=myDir[3]

phone=myDir[4]

office=myDir[5]

dept=myDir[6]

category=myDir[7]

myDir=[firstName, lastName, title, email, phone, office, dept, category]

employ=Employee()

Employee.setFirstName(employ, firstName)

Employee.setLastName(employ, lastName)

Employee.setPhone(employ, phone)

Employee.setTitle(employ, title)

Employee.setEmail(employ, email)

Employee.setOffice(employ, office)

Employee.setDept(employ, dept)

Employee.setCategory(employ, category)

#print (Employee.__str__(employ))

myDirectory[phone[-4:]]=myDir

#print (myDirectory)

return myDirectory

def firstpart(myDirectory):

  

  

inn=input("Enter the number for what you want. \n1. display entire directory\n2. look up by extension\n3.Remove an employee\n4.Add an employee\n5.Exit")

if inn=="1":

print (myDirectory)

elif inn=="2":

a = input ("Enter the extension number please.")

print (myDirectory[a])

elif inn =="3":

q=input ("please enter a phone number you would like to remove.")

del myDirectory[q]

print (myDirectory)

elif inn=="4":

z=input ("Please enter a phone number.")

myDirectory = myDirectory + {'phone':myDirectory[z] }

  

  

  

  

  

elif input=="5":

print ("you have now exited the program.")

dictionary = file_to_directory((f"../data/directory.txt"))

firstpart(dictionary)

Solutions

Expert Solution

dictionary in python stores key,value pair. So it assumes key to be unique for each insertion.

According to the given code,

So,in def file_to_directory(File), myDictionary is a dictionary. Here you are using myDirectory[phone[-4:]]=myDir to store the myDir which is a list of employee data. So myDictionary is assuming the last 4 digits of the phone number as a key. For Example: If the phone number is 9091190911, then myDictionary['0911']=myDir.

I suggest you to use phone as a key. not phone[-4:], using so will make a unique key to each employee. There may be a case where 2 persons have the same last 4 digits of a phone number. So better don't use that.

Coming to def firstpart(myDirectory):, here in menu 4, you basically have to add an employee with new phone number(Note: Does this mean adding the employee to the dictionary with phone number as a key? or updating the existing employee with a new phone number? The clarity is missing here. PLEASE clarify this in the comments section.). I assume, adding the employee to the dictionary with phone number as a key. So follow the code below.

elif inn=="4":

  z=input ("Please enter a phone number.")

  if z not in myDirectory.keys():

   #if phone not in myDirectory, then add it to the dictionary by entering the fname,lname,title etc..

    myDir=[firstName, lastName, title, email, phone, office, dept, category]  #please input all these data here
    myDirectory[z]=myDir  #this will add the employee(myDir) with new phone number as z.

Hope you understood the solution and where you are doing wrong. Feel free to ask doubts if any, in the comments section.

#Please don't forget to upvote if you find the solution helpful. Thank you.


Related Solutions

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...
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...
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:  ...
Using Python, I am trying to integrate 'iloc' into the line of code below? This line...
Using Python, I am trying to integrate 'iloc' into the line of code below? This line is replacing all the '1' values across my .csv file and is throwing off my data aggregation. How would I implement 'iloc' so that this line of code only changes the '1's integers in my 'RIC' column? patient_data_df= patient_data_df.replace(to_replace=[1], value ="Stroke") Thank you:)
I am trying to make a new code that uses functions to make it. My functions...
I am trying to make a new code that uses functions to make it. My functions are below the code. <?php */ $input; $TenBills = 1000; $FiveBills = 500; $OneBills = 100; $Quarters = 25; $Dimes = 10; $Nickels = 5; $Pennies = 1; $YourChange = 0; $input = readline("Hello, please enter your amount of cents:\n"); if(ctype_digit($input)) { $dollars =(int)($input/100); $cents = $input%100;    $input >= $TenBills; $YourChange = (int)($input/$TenBills); $input -= $TenBills * $YourChange; print "Change for $dollars dollars...
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,...
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...
In trying to apply my knowledge in the real world, I am trying to create a...
In trying to apply my knowledge in the real world, I am trying to create a realistic retirement schedule. However, I am running into difficulties using both a financial calculator as well as our equations from class in doing this. I am trying to do the following: plan a retirement schedule between the ages of 25 and 70, in which I would deposit 20% of my income each year. The income starts at 80,000 with an annual growth rate of...
1. I am trying to determine the level of measurement of my data type? I am...
1. I am trying to determine the level of measurement of my data type? I am looking for advice on Nominal, Ordinal, Interval, and Ratio 2. Does the data set have any categorical variables? I am trying to Describe the data set below in very general terms? This data consist of 8 variables: Which are GRE Scores, TOEFL Scores, University Rating, Statement of Purpose, Letter of Recommendation Strength, Undergraduate GPA, . Research Experience, and Chance of Admit. Name Type Description...
I am trying to start saving for retirement. I am investing all my cash into the...
I am trying to start saving for retirement. I am investing all my cash into the S&P 500, which will assume consistently 9.8% interest, compounded annually. I initially put a lump sum of $100 into my account, and I will deposit $10 every second week. a) After 10 years, how much money will I have invested? b) After 10 years, if I sold all of my stocks, how much money will I have in my account? c) After 25 years,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT