i'm receiving a key error for the below code. i'm reading a file called names.txt which has both name and age of a person. All names are in lower case but when i do name.lower() function while searching in the dictionary, it's throwing the key error.
fo = open('names.txt' ,'r')
data = fo.readlines()
fo.close()
dicti = {}
for i in data:
new_list = i.split(',')
dicti[new_list[0].lower()] = new_list[1].strip('\n')
name = input ('enter the name to be searched: ')
if name.lower() in dicti.keys():
print (dicti[name])
elif name == 'exit':
quit()
else:
print ('name ' + name.title() + ' not found')
file names.txt data is:
Sophia,35
Emma,28
Olivia,16
Isabella,10
Ava,9
Mia,26
Emily,4
Abigail,33
Can someone please tell me about the error.
Because of this:
if name.lower() in dicti.keys():
print (dicti[name])
You check that the lower-cased name is in the dicti, but then access it as is, without lower-case conversion. The proper code would be:
if name.lower() in dicti.keys():
print (dicti[name.lower()])
Related
Screenshot of the CSV file I am inputting
This is my code that I am trying to run. I am trying to make call functions to make the program run. get_toc_tuple is supposed to split the lines in columns. read_toc is supposed to read the file and copy the columns to a list. get_cell is one of the options you would be able to do. Eventually I want to be able to get_work_phone and get_shift. print_cell is supposed to print the correct info for name and cell phone number.
I can't figure out why these call functions are not working.
It is only printing:
Team Member Cell Phone
My Code:
import re
def get_toc_tuple(line_str):
data = re.split(r'\s{2,}', line_str)
team_member = data[0]
desk_phone = data[2]
cell_phone = data[3]
shift = data[4]
return (team_member, desk_phone, cell_phone, shift)
def read_toc(filename):
fileread = open(filename, 'r')
toc_list = []
fileread.readlines()[0]
for line in fileread.readlines()[1:]:
toc_list.append(get_toc_tuple(line.strip()))
fileread.close()
return toc_list
def get_cell(toc_list):
cell_list = []
for tup in toc_list:
if name in tup[0]:
cell_list.append(tup[3])
return cell_list
def print_cell(cell_list):
print('%-19s%-1s%-13s\n' % ('Team Name', ' ', 'Cell Phone'))
for line in cell_list:
team_member = line[0]
cell_phone = line[3]
print('%-19s%-1s%-13s\n' % (team_member, ' ', cell_phone))
if __name__ == '__main__':
option = input("Cell Phone, Work Phone, or Shift? ")
name = input('Employee: ')
filename = input('Select a file location: ')
toc_list = read_toc(filename)
if option == 'Cell Phone':
cell_list = get_cell(toc_list)
print_cell(cell_list)
[1]: https://i.stack.imgur.com/ZrblW.png
These kind of problems are easiest to solve using the csv module. Try to export your file in csv format (using excel or any other tool):
Team Member,Title,Desk Phone,Cell Phone,Shift
Bob Smith,Technical Support,xxx-xxx-xxxx,xxx-xxx-xxx,M-F 8a-5p
Todd Wilson,Technical Support,616-233-5065,734-709-1472,M-F 8a-5p
Then use:
import csv
rows = []
file = open("D:/team.csv")
with file:
read = csv.DictReader(file)
for row in read:
rows.append(dict(row))
After above code is executed, rows list will contain the rows in the file mapped on the header row items:
[{'Team Member': 'Bob Smith', 'Title': 'Technical Support', 'Desk Phone': 'xxx-xxx-xxxx', 'Cell Phone': 'xxx-xxx-xxx', 'Shift': 'M-F 8a-5p'}, {'Team Member': 'Todd Wilson', 'Title': 'Technical Support', 'Desk Phone': '616-233-5065', 'Cell Phone': '734-709-1472', 'Shift': 'M-F 8a-5p'}]
Once you have this list is very easy to parse it and extract any info you want. For example Desk phone and Shift for Team Member Todd Wilson, will be something like:
for row in rows:
if row['Team Member'] == 'Todd Wilson':
print(row['Desk Phone'], row['Shift'])
I have gotten mostly through this assignment but I am stuck as to obtain the proper outputs.
This assignment wishes that if the inputs are a full name, that the outputs are "last name, first initial. last initial. If the input was Stacy Estel Graham, the expected output should be Graham, S.E.
"Many documents use a specific format for a person's name. Write a program whose input is:
firstName middleName lastName
and whose output is:
lastName, firstInitial.middleInitial."
full_name = input()
mod_name = full_name.split(' ')
last_name= mod_name.pop(-1)
mod_name.join('.')
print(last_name)
print(mod_name)
I am completely lost on how to proceed.
You need to use '.'.join() to get the initials added.
To extract only the first char from the name, you can do mod_name[i][:1] where i is the index from 0 until last name - 1.
You can do something like this:
full_name = input('Enter your full name :')
mod_name = full_name.split(' ')
temp = '.'.join([mod_name[i][0] for i in range (0, len(mod_name) - 1)])
if temp == '':
print (mod_name[-1])
else:
print (mod_name[-1] + ', ' + temp + '.')
Here are some of the sample runs:
Enter your full name :Stacy Estel Sugar Graham
Graham, S.E.S.
Enter your full name :Stacy Estel Graham
Graham, S.E.
Enter your full name :Stacy Graham
Graham, S.
Enter your full name :Graham
Graham
Use:
def format_name(name):
names = name.split()
return f"{names[-1]}, {''.join([f'{i[0]}.' for i in names[:-1]])}"
Examples:
format_name('Stacy Estel Graham')
# > 'Graham, S.E.'
format_name('Randall McGrath')
# > 'McGrath, R.'
this code help you,but middle name is must for every person for creating your desire output
import re
s="Stacy Estel Graham"
words=s.split()
k=re.findall("[A-Z]",s)
p=words[-1]+","+k[0]+"."+k[1]
print(p)
Output:
Graham,S.E
Not with re :
full_name = input()
mod_name = full_name.split(' ')
last_name= mod_name.pop(-1)
first_inital = mod_name[0][0]
if len(mod_name) >= 2:
middle_inital = mod_name[1][0]
print(f'{last_name}, {first_inital}.{middle_inital}')
else:
print(f'{last_name}, {first_inital}.')
You can use string indexing and f' string format.
Input:
Hello World Python
Output:
Python, H.W.
full_name = input(')
mod_name = full_name.split(' ')
temp = '.'.join([mod_name[i][0] for i in range (0, len(mod_name) - 1)])
if temp == '':
print (mod_name[-1])
else:
print (mod_name[-1] + ', ' + temp + '.')
I am a beginner of python, I have an assignment that wants me to read a csv file and print out the related information.
I have an excel file which includes student's ID, school and hobby.
now I want to write a program to show the detail of the student by entering the ID.
requirements are:
print the entire row when ID is correctly input
print "Empty, try again" when ID input is space
print "No record" when the input is invalid or there is no matching record
I manage to fulfill the first 2 requirements but have no idea how to get the third. Seems like my code is always looping through each of the data and print "No record" every time, i.e. if there are 3 records, 3 "No record" will be printed. Could someone help me with it? Much thanks! Below will be my code.
import csv
file = "a.csv"
sID = input("Enter ID: ")
while (sID == " "):
print("Empty input,enter again")
sID = input("Enter ID: ")
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (sID == row["id"]):
print("{0}{1}{2}".format(row[id],row[school],row[hobby])
else:
print("No record")
You need a few changes:
You should use the str.strip() method to test if a string is empty so that it accounts for any number of spaces.
You should quote the column names to make them string literals when using them as indices to access the value of a column in the current row.
You should use the optional else block for your for loop to determine that there is no matching record found, and break the loop if there is one found.
You are missing a right parenthesis for the print call that outputs a row.
With the above changes, your code should look like:
import csv
file = "a.csv"
sID = input("Enter ID: ")
while not sID.strip():
print("Empty input,enter again")
sID = input("Enter ID: ")
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (sID == row["id"]):
print("{0}{1}{2}".format(row['id'],row['school'],row['hobby']))
break
else:
print("No record")
I have a text file named "paintingJobs". The data looks like this:
E5341,21/09/2015,C102,440,E,0
E5342,21/09/2015,C103,290,A,290
E5343,21/09/2015,C104,730,N,0
E5344,22/09/2015,C105,180,A,180
I have written a program that only finds the first entry but cannot find any data beyond the first line (I think it is to do with Python including /n in front of the username) The program looks like this.
def ASearch():
print("Option A: Search for an estimate")
print("Please enter the estimate number: ")
estimateNumber = str(input())
file = open("paintingJobs.txt", "r")
paintJobs = file.readlines()
file.close()
length = len(paintJobs)
paintData = []
for line in paintJobs:
estNumber, estDate, CustID, FinalTotal, Status, AmountPaid = line.split(",")
if estimateNumber == estNumber:
print("Estimate number: ", estNumber)
print("Customer ID: ", CustID)
options()#this is a function in a for a different part of the program that works fine
else:
print("You have entered an incorrect estimate number; please try again")
ASearch()
How do I get the program to read (and return the values of) the second entry in the list E.G. E5342 (any help would be appreciated greatly)
def autocorrect(word):
Break_Word = sorted(word)
Sorted_Word = ''.join(Break_Word)
return Sorted_Word
user_input = ""
while (user_input == ""):
user_input = input("key in word you wish to enter: ")
user_word = autocorrect(user_input).replace(' ', '')
with open('big.txt') as myFile:
for word in myFile:
NewWord = str(word.replace(' ', ''))
Break_Word2 = sorted(NewWord.lower())
Sorted_Word2 = ''.join(Break_Word2)
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
Basically when I had a dictionary of correctly spelled word in "big.txt", if I get the similar from the user input and the dictionary, I will print out a line
I am comparing between two string, after I sort it out
However I am not able to execute the line
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
When I try hard code with other string like
if ("a" == "a"):
print("The word",user_input,"exist in the dictionary")
it worked. What wrong with my code? How can I compared two string from the file?
What does this mean? Does it throw an exception? Then if so, post that...
However I am not able to execute the line
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
because I can run a version of your program and the results are as expected.
def autocorrect(word):
Break_Word = sorted(word)
Sorted_Word = ''.join(Break_Word)
return Sorted_Word
user_input = ""
#while (user_input == ""):
user_input = raw_input("key in word you wish to enter: ").lower()
user_word = autocorrect(user_input).replace(' ', '')
print ("user word '{0}'".format(user_word))
for word in ["mike", "matt", "bob", "philanderer"]:
NewWord = str(word.replace(' ', ''))
Break_Word2 = sorted(NewWord.lower())
Sorted_Word2 = ''.join(Break_Word2)
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
key in word you wish to enter: druge
user word 'degru'
The word druge doesn't exist in the dictionary
key in word you wish to enter: Mike
user word 'eikm'
('The word','mike', 'exist in the dictionary')
Moreover I don't know what all this "autocorrect" stuff is doing. All you appear to need to do is search a list of words for an instance of your search word. The "sorting" the characters inside the search word achieves nothing.