How to write a function to print out a item in dictionary? - python

I am trying to define and call a function but I am stuck on what to put all I know currently is that I definitely need a for loop .
I want my output to be 867-5309
from an input of
Input 1: Joe 123-5432 Linda 983-4123 Frank 867-5309
Input 2: Frank
Though obviously I need it to work for any input that is placed into the name input
def get_phone_number(my_dict, contact_name):
phone_number = ''
return phone_number
if __name__ == '__main__':
word_pairs = input()
my_list = word_pairs.split()
name = input()
my_dict = {}
for i in range(0, len(my_list), 2):
my_dict[my_list[i]] = my_list[i + 1]
print(get_phone_number(dict, name))
I already know my dictionary works fine my only problem is with formatting a function that will give me the output I want, I am struggling with functions and just need a little help to get the result I want.

You don't need a function for this. And least of all a loop. You can just call the entry of my_dict using the key:
if __name__ == '__main__':
word_pairs = input("Enter Words: ")
my_list = word_pairs.split()
name = input("Enter Name: ")
my_dict = {}
for i in range(0, len(my_list), 2):
my_dict[my_list[i]] = my_list[i + 1]
print(my_dict[name])

Related

Why is my code not posting the requested columns in main def?

I don't expect any coding answers, more just guidance. For my project I have to date-mine apple stock prices from a csv-file and implement it in my code. I provided a sample output below.
https://imgur.com/rPOPN1I
Right now, I am not getting any error messages but my code is not posting the columns requested from the csv.file. Are my definitions at fault or am I missing something else?
# Project No.: 5
# Author: burntchickennuget
# Description: making definitions, reading from a .csv file, validating input, data-mining,
f_list = list()
file_object = ()
my_tot = dict()
new_list = list()
def get_input_descriptor():
while True:
filename = input("Enter a file name: ")
if filename == 'table.csv':
with open(filename, "r") as infile:
infile.readlines()[1:]
# for line in lines:
# print(line.rstrip())
break
else:
print("Bad file name, try again")
return filename
def get_data_list(file_object, column_number):
dict = {}
for val in file_object:
date = val.split(",")[0]
data = float(val.split(",")[column_number])
dict[date] = data
return dict.items()
def average_data(new_list):
for date, price in new_list:
my_tot[date] = my_tot.get(date, 0) + float(price)
my_times[date] = my_times.get(date, 0) + 1
for key in my_tot:
f_list.append((float(my_tot[key] / my_times[key]), key))
def main():
get_input_descriptor()
column_number = int(input("Which column: "))
date_list = get_data_list(file_object, column_number)
final_list = average_data(date_list)
x = sorted(f_list)
print('Lowest 6:')
for tup in x[:6]:
print
tup[0], tup[1]
print('Highest 6:')
x = sorted(f_list, reverse=True)
for tup in x[:6]:
print
tup[0], tup[1]
while 1:
flag = input("do you want to continue? ")
if flag == '' or not flag[0].lower() in ['y', 'n']:
print("Please answer with a yes or no")
else:
break
if flag[0].lower() == 'y':
column = input("Which column: ")
print(column)
if flag[0].lower() == 'n':
print("Bye!")
if __name__ == "__main__":
main()
What can I try next?
Take a look around your get_input_descriptor method.
What are you returning from the method?
Where is the returned information being stored in the main method (is it being stored at all?)
What are you doing with the lines that you read from the file?
What is the file_object you are passing into get_data_list
My main advice would be to add print everywhere for debugging. See what it stored in your variables at different points in the program and see where a variable doesn't contain what you think it should

Is there a way I could pair up the contents of an array that can delete itself later? (Secret Santa Program)

I'm trying to make a Secret Santa program. Ideally the program should ask for at least three names, and afterwards the program asks if there are more names. If yes, open up another text field and add it to the list of names. If no, break the loop, create a separate list with the names inside it, shuffle the second list of names, and pair them up with a name from the original list.
For example, if John, Elliot, Sarah and Jenny put in their names and the program shuffled their names, it should output something like this:
[('John', 'Sarah'), ('Elliot', 'John'), ('Sarah', 'Jenny'), ('Jenny', 'Elliot')]
But instead I get something like:
[('John', 'John'), ('Elliot', 'John'), ('Sarah', 'Elliot'), ('Jenny', 'Jenny')]
Here's the code:
import sys
import random
names = []
class Santa:
#The class that takes the values, shuffles them, pairs and then displays them
def __init__(self, name):
self.turns = name
self.people = names
self.final = []
def sort_names(self):
random.shuffle(self.people)
for name in self.turns:
pair = (name, random.choice(self.people))
if pair[0] == [1]:
pair = (name, random.choice(self.people))
else:
self.final.append(pair)
def print_name(self):
input("\nNames are ready! Press Enter to show the names.")
print(self.final)
def main():
# The function asking for user input
name = input("\nType in your name. ")
names.append(name)
name = input("\nType in the next name. ")
names.append(name)
name = input("\nType in the next name. ")
names.append(name)
while True:
next = input("\nIs this everyone? Y/N ")
if next.upper() == "Y":
break
elif next.upper() == "N":
name = input("\nType in the next name. ")
names.insert(0, name)
else:
print("\nInvalid response, please try again.")
print(names)
start = Santa(names)
start.sort_names()
start.print_name()
input("\nRecord these, and press enter to quit.")
sys.exit()
main()
You shouldn't need an entire class to set this up, and I have tried to clean up a little of reading input.
import random
names = []
for _ in range(3):
name = input("\nType in your name. ")
names.append(name)
while True:
next = input("\nIs this everyone? Y/N ")
if next.upper() == "Y":
break
elif next.upper() == "N":
name = input("\nType in the next name. ")
names.insert(0, name)
else:
print("\nInvalid response, please try again.")
print(names)
random.shuffle(names)
pairs = [(first_person, second_person) for first_person, second_person in zip(names, names[1:] + [names[0]])]
print(pairs)
Your problem is the comparison so you do not draw yourself:
for name in self.turns:
pair = (name, random.choice(self.people))
# you compare against [1] ? That is a list containing a 1 as only thing
# and it will never be True unless if you compare string vs. name
if pair[0] == [1]:
pair = (name, random.choice(self.people))
else:
self.final.append(pair)
You can streamline your loop and you have to handle odd/even number of names when pairing people up. Using list slicing and zipping makes it easier to pair up people.
Example:
import sys
import random
class Santa:
def __init__(self, names):
self.people = names
def shuffle(self):
random.shuffle(self.people)
self.final = []
if len(self.people) < 2:
print("Sorry, not enough people to gift stuff around")
return
# taken from the comment, because superior to what I had originally
# see edit history for my solution ;o) - this one suggested by #Matthias
self.final = [(n1, n2) for n1, n2 in zip(names, names[1:] + [names[0]])]
def print_name(self):
print(self.final)
name = "dummy"
names = []
while name:
name = input(f"Whats the {len(names)+1}. name? (Empty to end) ").strip()
if not name:
break
names.append(name)
print(names)
santa = Santa(names)
santa.shuffle()
santa.print_name()
Output (omitted input outputs):
# odd inputs
['Tim', 'John', 'Luise', 'Maria', 'Wasja']
[('Wasja', 'Maria'), ('Maria', 'John'), ('Luise', 'Tim')]
['Tim', 'John', 'Luise', 'Maria', 'Wasja']
[('Maria', 'Wasja'), ('Wasja', 'Tim'), ('John', 'Luise')]
# even inputs
['Tim', 'John', 'Luise', 'Maria']
[('John', 'Tim'), ('Maria', 'Luise')]
['Tim', 'John', 'Luise', 'Maria']
[('Luise', 'Tim'), ('John', 'Maria')]
You can read more about zip and list slicing here:
Zip lists in Python
Understanding slice notation

how can i rearrange the letters in the name with this code

there are 3 errors in the code, can you guys please help me find them, I am just a beginner. I need to append (concatenate) the letter from Var1 to namelist variable, which is a list variable. But there seems to be a problem as i is a string.
namelist = []
var1 = input( "Enter the name you want to validate ").upper()
namelist.append(var1[0])
for i in var1[1:]:
for j in (namelist):
if(j>=i):
namelist.insert(i,namelist.index(j))
break
else:
i.append(namelist)
print(namelist)
expected result: to run the code swiftly to rearrange letters in the name
its seems like you vwant to reverse string
there are several ways, here are some with basic for loop
namelist = []
var1 = input( "Enter the name you want to validate ").upper()
for i in range(1, len(var1) + 1):
namelist.append(var1[len(var1) - i])
print (namelist)
print ("".join(namelist))
output:
Enter the name you want to validate Hello
['O', 'L', 'L', 'E', 'H']
OLLEH
.
namelist = ''
var1 = input( "Enter the name you want to validate ").upper()
for i in range(1, len(var1) + 1):
namelist = namelist + var1[len(var1) - i]
print (namelist)
output:
Enter the name you want to validate hello
OLLEH
.
def reverse(text):
rev_text = ""
for char in text:
rev_text = char + rev_text
return rev_text
print (reverse("hello"))
output:
olleh
First of all, please use clear names for variables.
What exactly do you want to reach with your code?
You can use this code to get an list of the letters:
NameList = []
Input = input("Enter the name you want to validate:\n").upper()
for Character in Input:
NameList.append(Character)
print(NameList)
And set a variable to the reverse with:
NameList = []
Input = input("Enter the name you want to validate:\n").upper()
for Character in Input:
NameList.append(Character)
Output = "".join(NameList[::-1])

I am trying to create an address book program that will append user input to its appropriate list

I am having trouble getting past writing user input to my list what am I doing wrong here? This is an address book program that I am writing, the assignment is to create parallel lists that will store user input data in the appropriate list using a for or while loop. The program must also have a search function which you can see is at the bottom of the code. My issue that I am having is getting the program to store data within my lists. Unfortunately lists are something that give me lots of trouble I just cant seem to wrap my head around it no matter how much research I have done. The issue im running into is the append.data function when trying to write lastname and firstname to my list of names. what am I doing wrong?
#NICHOLAS SHAFFER
#5/11/2016
#MYADDRESSBOOK
def menu():
index = 0
size = 100
count = 0
answer = raw_input("Are You Creating An Entry [Press 1] \nOr Are You Searching An Entry [Press 2] ")
if answer == "1" :
print ("This is where we create")
append_data(index, size, count)
elif answer == "2" :
print ("this is where we search")
search_database()
name[size]
phone[size]
addresss[size]
# IF we are creating
def append_data(index, size, count):
# collect information
for index in range(0, 100):
optOut = 'no'
while optOut == 'no':
lastname[count] = raw_input("What is the persons last name? ")
firstname[count] = raw_input("What is the persons first name? ")
phone[count] = raw_input("What id the persons phone number? ")
address[count] = raw_input("What is the persons address? ")
count = count + 1
print 'Would you like to create another entry?'
optOut = raw_input('Would you like to create another entry? [ENTER YES OR NO]:')
if optOut == 'yes':
menu()
#create string to print to file
#print temp1
#print (firstname + " " + lastname + ", " + phone + ", " + email + ", " + address)
print listName[index]
print listPhone[index]
print listAddress[index]
print 'file has been added to your addressbook sucessfuly'
menu()
# SEARCHING FOR A RECORD
def search_database():
searchcriteria = raw_input("Enter your search Criteria, name? phone, or address etc ")
print searchcriteria
if searchcriteria == "name":
temp1 = open(listName[lastname, firstname],"r")
print temp1
if searchcriteria == "phone":
temp1 = open(listPhone[0], "r")
print temp1
if searchcriteria == "address":
temp1 = open(listAddress[0], "r")
print temp1
else:
print "sorry you must enter a valid responce, try again."
menu()
for line in temp1:
if searchcriteria in line:
print line
errorMessage()
# USER DID NOT PICK CREATE OR SEARCH
def errorMessage():
print ("Incorrect Answer")
exit()
menu()
Your error message says it all:
line 34, in append_data lastname[count]... NameError: global name 'lastname' is not defined
You'll get this same error if you type lastname[4] in any interpreter -- you've simply never defined a list called lastname, so you can't access items in it. In the short term, you can fix this with a line
lastname = list()
You're going to end up with more troubles though; lastname won't be accessible outside the function where you define it, neither will listName. I'd probably approach that by writing them into a data file/database, or maybe creating a quick class whose members will all have access to self.lastname.
My final append for lists thanks again Noumenon
def append_data(index, size, count):
lastnames = list()
if count < size -1:
lastname = raw_input("What is the persons last name? ")
lastnames.append(lastname)
print lastnames
firstnames = list()
if count < size - 1:
firstname = raw_input("What is the persons first name? ")
firstnames.append(firstname)
print firstnames
phones = list()
if count < size - 1:
phone = raw_input("What id the persons phone number? ")
phones.append(phone)
print phones
addresss = list()
if count < size - 1:
address = raw_input("What is the persons address? ")
addresss.append(address)
print addresss
listName = (lastnames, firstnames)
addressbook =(listName, phones, addresss)
index = index + 1
count = count + 1
print addressbook
optOut = raw_input('Would you like to create another entry? [Enter YES or NO]: ')
if optOut == 'YES':
menu()
print 'file has been added to your addressbook sucessfuly'
menu()

Python - print statistics from one file into another

import sys
import pickle
import string
def Menu():
print ("***********MENU************")
print ("0. Quit")
print ("1. Read text file")
print ("2. Display counts")
print ("3. Display statistics of word lengths")
print ("4. Print statistics to file")
def readFile():
while True:
fileName = input("Please enter a file name: ")
if (fileName.lower().endswith(".txt")):
break
else:
print("That was an incorrect file name. Please try again.")
continue
return fileName
THE_FILE = ""
myDictionary = 0
def showCounts(fileName):
numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0
with open(fileName, 'r') as f:
for line in f:
wordCount+=len(line.split())
lineCount+=1
for char in line:
if char.isdigit() == True:
numCount+=1
elif char == '.':
dotCount+=1
elif char == ',':
commaCount+=1
print("Number count: " + str(numCount))
print("Comma count: " + str(commaCount))
print("Dot count: " + str(dotCount))
print("Line count: " + str(lineCount))
print("Word count: " + str(wordCount))
def showStats(fileName):
temp1 = []
temp2 = []
lengths = []
myWords = []
keys = []
values = []
count = 0
with open(fileName, 'r') as f:
for line in f:
words = line.split()
for word in words:
temp2.append(word)
temp1.append(len(word))
for x in temp1:
if x not in lengths:
lengths.append(x)
lengths.sort()
dictionaryStats = {}
for x in lengths:
dictionaryStats[x] = []
for x in lengths:
for word in temp2:
if len(word) == x:
dictionaryStats[x].append(word)
for key in dictionaryStats:
print("Key = " + str(key) + " Total number of words with " + str(key) + " characters = " + str(len(dictionaryStats[key])))
return dictionaryStats
def printStats(aDictionary):
aFile = open("statsWords.dat", 'w')
for key in aDictionary:
aFile.write(str(key) + " : " + str(aDictionary[key]) + "\n")
aFile.close()
choice = -1
while choice !=0:
Menu()
choice = (int(input("Please choose 1-4 to perform function. Press 0 to exit the program. Thank you. \n")))
if choice == 0:
print ("Exit program. Thank you.")
sys.exit
elif choice == 1:
THE_FILE = readFile()
elif choice == 2:
showCounts(THE_FILE)
elif choice == 3:
showStats(THE_FILE)
elif choice == 4:
printStats(myDictionary)
else:
print ("Error.")
I'm trying to open a file, have it display the statistics of the word lengths, and then have it make a new file with the statistics of the word lengths. I can read the file and have it display the statistics, but when I print the statistics to file I get an error - "int" object is not iterable. Any ideas? Thanks guys!
Error:
Traceback (most recent call last):
File "hw4_ThomasConnor.py", line 111, in <module>
printStats(myDictionary)
File "hw4_ThomasConnor.py", line 92, in printStats
for key in aDictionary:
TypeError: 'int' object is not iterable
The problem is that you set myDictionary to 0 at the top of your program, and then are sending it to your file writing function here printStats(myDictionary).
In this function you have this line for key in aDictionary, and since you passed in 0, this is effectively for key in 0 which is where the error comes from.
You need to send the result of the showStats function to your printStats function.
As this is looking like homework, I will leave it at that for now.
Sorry I am confused. in the showStats function I have to somehow say
"send results to printStats function" and then in the printStats
function I have to call the results? How would I do that exactly?
The printStats function is expecting a dictionary to print. This dictionary is generated by the showStats function (in fact, it returns this dictionary).
So you need to send the result of the showStats function to the printStats function.
To save the return value of a method, you can assign it on the LHS (left hand side) of the call expression, like this:
>>> def foo(bar):
... return bar*2
...
>>> def print_results(result):
... print('The result was: {}'.format(result))
...
>>> result = foo(2) # Save the returned value
Since result is just like any other name in Python, you can pass it to any other function:
>>> print_results(result)
The result was: 4
If we don't want to store the result of the function, and just want to send it to another function, then we can use this syntax:
>>> print_results(foo(2))
The result was: 4
You need to do something similar in your main loop where you execute the functions.
Since the dictionary you want to print is returned by the showStats function, you must call the showStats function first before calling the printStats function. This poses a problem if your user selects 4 before selecting 3 - make sure you find out a work around for this. A simple work around would be to prompt the user to calculate the stats by selecting 3 before selecting 4. Try to think of another way to get around this problem.
Here:
THE_FILE = ""
myDictionary = 0
you set integer to myDictionary.
and later you do:
printStats(myDictionary)
and as you try to interate over keys of dictionary inside, you fail.

Categories

Resources