find key in dictionary and print value - python

Hello everyone I am stuck on a class assignment and not sure where to go at this point as my college does not offer tutors for the programming field as this is the first semester that this has been offered. Assignment is:
Write a program that:
Prints out the toy name for that code in a useful message such as, ‘The toy for that code is a Baseball’
The program exits when instead of a toy code, the user enters ‘quit’
below is a sample of the text file that the dict is suppose to populate from
D1,Tyrannasaurous
D2,Apatasauros
D3,Velociraptor
D4,Tricerotops
D5,Pterodactyl
T1,Diesel-Electric
T2,Steam Engine
T3,Box Car
and what I have gotten so far is:
**
fin=open('C:/Python34/Lib/toys.txt','r')
print(fin)
toylookup=dict() #creates a dictionary named toy lookup
def get_line(): #get a single line from the file
newline=fin.readline() #get the line
newline=newline.strip() #strip away extra characters
return newline
print ('please enter toy code here>>>')
search_toy_code= input()
for toy_code in toylookup.keys():
if toy_code == search_toy_code:
print('The toy for that code is a','value')
else:
print("toy code not found")
**
and to be honest I am not even sure I am right with what I have. any help at all would be greatly appreciate thank you.

There are two issues.
Your dictionary isn't getting populated; however there currently isn't enough info in your question to help with that problem. Need to know what the file looks like, etc.
Your lookup loop won't display the values for keys that match. Below is the solution for that.
Try iterating over key:value pairs like this:
for code, toy in toylookup.items():
if key == search_toy_code:
print('The toy for that code ({}) is a {}'.format(code, toy))
else:
print("Toy code ({}) not found".format(code))
Take a look at the docs for dict.items():
items():
Return a new view of the dictionary’s items ((key, value) pairs).

You should make yourself familiar with basic python programming. In order to solve such tasks you need to know about basic data structures and loops.
# define path and name of file
filepath = "test.txt" # content like: B1,Baseball B2,Basketball B3,Football
# read file data
with open(filepath) as f:
fdata = f.readlines() # reads every line in fdata
# fdata is now a list containing each line
# prompt the user
print("please enter toy code here: ")
user_toy_code = input()
# dict container
toys_dict = {}
# get the items with toy codes and names
for line in fdata: # iterate over every line
line = line.strip() # remove extra whitespaces and stuff
line = line.split(" ") # splits "B1,Baseball B2,Basketball"
# to ["B1,Baseball", "B2,Basketball"]
for item in line: # iterate over the items of a line
item = item.split(",") # splits "B1,Baseball"
# to ["B1", "Baseball"]
toys_dict[item[0]] = item[1] # saves {"B1": "Baseball"} to the dict
# check if the user toy code is in our dict
if user_toy_code in toys_dict:
print("The toy for toy code {} is: {}".format(user_toy_code, toys_dict[user_toy_code]))
else:
print("Toy code {} not found".format(user_toy_code))

Related

How can I remove double quotations surrounding a list imported from a file in Python?

I'm trying to create a food storage application that tracks the items put in a food storage facility and recalls them for the user. This is a very early prototype of the program, only capable of tracking the information locally, but I ran into some problems with it. So my apologies if this code is unreadable, I just can't find a solution to my problem explained below.
print("Food Storage Application V1.0 - LOCAL ONLY")
UPC_List = []
with open('UPCList.txt', 'r') as file:
for UPCentry in file:
location = UPCentry[:-1]
UPC_List.append(location)
print(UPC_List)
global i
i = 0
UPC_Input = ''
UPC_Count = 0
while True:
UPC_Found = False
UPC_Input = input("Enter UPC or enter 'end' to quit: ")
if UPC_Input == "end":
with open("UPCList.txt", "w") as file:
for UPCsave in UPC_List:
file.write('%s\n' % UPCsave)
break
try:
UPC_Input = int(UPC_Input)
except ValueError as v:
print(f"Input '{UPC_Input}' is not an acceptable UPC")
continue
# print(UPC_List) # for debugging
def newProduct(UPC):
global UPC_Count
product_name = input(f"Enter name of item {UPC}: ")
product_quantity = input(f"Enter quantity of item {UPC}: ")
try:
product_quantity = int(product_quantity)
except ValueError as v:
print("Invalid quantity. Please enter a number.")
newProduct(UPC_Input)
product_unit = input(f"Enter unit type (box, bunch, can, etc...) of item {UPC}: ")
print(f"You have added: \n {product_name} \n {UPC} \n Quantity: {product_quantity} \n Unit: {product_unit}")
UPC_List.insert(UPC_Count, [UPC, product_name, product_quantity, product_unit])
UPC_Count += 1
def existingProduct(UPC):
for sublist in UPC_List:
if str(UPC) in str(sublist):
UPC = int(UPC)
print(f"Position: {UPC_List.index(sublist)} {sublist.index(UPC)}")
position = UPC_List.index(sublist)
addition = input(f"Enter the number of items to add to '{UPC_List[position][1]}' (Default entry: +1): ")
try:
addition = int(addition)
except ValueError as v:
addition = 0
if addition == 0:
UPC_List[position][2] += 1
else:
UPC_List[position][2] += addition
print(f"New Quantity for item '{UPC_List[position][1]}': {UPC_List[position][2]}")
#Find if UPC Exists
for UPC in UPC_List:
if UPC[0] == UPC_Input:
print("UPC Found")
existingProduct(UPC_Input)
UPC_Found = True
if UPC_Found == False:
newProduct(UPC_Input)
This is my code so far. I made a version of it without the read and writing to file lines and it worked great, but I'm stumped on getting the code to read a list from a file and use it in the code. It saves the list, but it won't retrieve it correctly. I found what I think is the problem by using that print(UPC_List) line, which prints ["[2, 'banana', 2, 'bunch']"] (that was a test entry I loaded into the file using the program). I think the problem lies in the double quotes on the outside of the list. This is a nested list, so those quotation marks lead to an index error when I try to access the list.
If this isn't enough info, I can try to provide more. I'm very new to python and coding in general so this was my best attempt at the script.
You are reading each list in as a string.
You can use the python eval function to convert a string into its evaluated form:
my_list_string = "['item1', 'item2']"
my_list = eval(my_list_string)
To reproduce and solve, we need a minimal reproducible example including
the input (file contents posted as plain-text in code-block formatting)
the minimal code to reproduce
Input file
Contents of UPCList.txt:
[2, 'banana', 2, 'bunch']
This is the string-representation of a list in Python (like str(list)). Probably it was written by your program.
Code
a minimal reproducible example (only first few lines to print the read list):
upc_locations = []
with open('UPCList.txt', 'r') as file:
for upc in file:
location = upc[:-1]
upc_locations.append(location)
print(upc_locations)
Prints:
["[2, 'banana', 2, 'bunch']"]
Debug
add some debug print for each line read
upc_locations = []
with open('UPCList.txt', 'r') as file:
for line in file:
print(line)
location = line[:-1] # read all chars from line until last (excluding)
print(location)
upc_locations.append(location)
print(upc_locations)
Prints:
[2, 'banana', 2, 'bunch']
[2, 'banana', 2, 'bunch']
["[2, 'banana', 2, 'bunch']"]
Note:
the second empty-line is the line-break \n at the end of the file's line.
the first line contains something like a Python list with strings and numbers
the third line has removed the line-break.
Fix
The line can be parsed as JSON array. Therefore we need to replace the single-quotes by double-quotes first.
import json
upc_locations = []
with open('UPCList.txt', 'r') as file:
for line in file:
cleaned = line.strip() # remove the line-break and any surrounding whitespace
print(cleaned)
valid_json = cleaned.replace("'", '"') # replace single quotes by double quotes to have valid JSON strings
array = json.loads(valid_json)
print(array)
for element in array:
upc_locations.append(element)
print(upc_locations)
Prints:
[2, 'banana', 2, 'bunch']
[2, u'banana', 2, u'bunch']
[2, u'banana', 2, u'bunch']
Tip: save your objects as JSON to a file
When saving objects from your programs to a plain text-file it is recommended to use a standard format like CSV, XML or JSON.
So you can use standard-parsers to read it (back).
For example:
import json
def save(list):
with open("UPCList.txt", "w") as file:
json.dump(list, file)
# file.write('%s\n' % UPCsave)
def load():
with open("UPCList.txt", "r") as file:
return json.load(file)
Note:
The out-commented line wrote the list in Python's string-representation (see precent-formatting %s). Thus we had to replace the double-quotes when reading.
The json-dump writes a list as JSON-array. This format is readable by many programs and tools and the defacto web-standard.
See also:
Write JSON objects to file using python
Reading JSON from a file?

Removing '\n' from a string without using .translate, .replace or strip()

I'm making a simple text-based game as a learning project. I'm trying to add a feature where the user can input 'save' and their stats will be written onto a txt file named 'save.txt' so that after the program has been stopped, the player can then upload their previous stats and play from where they left off.
Here is the code for the saving:
user inputs 'save' and class attributes are saved onto the text file as text, one line at a time
elif first_step == 'save':
f = open("save.txt", "w")
f.write(f'''{player1.name}
{player1.char_type} #value is 'Wizard'
{player1.life}
{player1.energy}
{player1.strength}
{player1.money}
{player1.weapon_lvl}
{player1.wakefulness}
{player1.days_left}
{player1.battle_count}''')
f.close()
But, I also need the user to be able to load their saved stats next time they run the game. So they would enter 'load' and their stats will be updated.
I'm trying to read the text file one line at a time and then the value of that line would become the value of the relevant class attribute in order, one at a time. If I do this without converting it first to a string I get issues, such as some lines being skipped as python is reading 2 lines as one and putting them altogether as a list.
So, I tried the following:
In the below example, I'm only showing the data from the class attributes 'player1.name' and 'player1.char_type' as seen above as to not make this question as short as possible.
elif first_step == 'load':
f = open("save.txt", 'r')
player1.name_saved = f.readline() #reads the first line of the text file and assigns it's value to player1.name_saved
player1.name_saved2 = str(player1.name_saved) # converts the value of player1.name_saved to a string and saves that string in player1.name_saved2
player1.name = player1.name_saved2 #assigns the value of player1.name_saved to the class attribute player1.name
player1.char_type_saved = f.readlines(1) #reads the second line of the txt file and saves it in player1.char_type_saved
player1.char_type_saved2 = str(player1.char_type_saved) #converts the value of player1.char_type_saved into a string and assigns that value to player1.char_type_saved2
At this point, I would assign the value of player1.char_type_saved2 to the class attribute player1.char_type so that the value of player1.char_type enables the player to load the previous character type from the last time they played the game. This should make the value of player1.char_type = 'Wizard' but I'm getting '['Wizard\n']'
I tried the following to remove the brackets and \n:
final_player1.char_type = player1.char_type_saved2.translate({ord(c): None for c in "[']\n" }) #this is intended to remove everything from the string except for Wizard
For some reason, the above only removes the square brackets and punctuation marks but not \n from the end.
I then tried the following to remove \n:
final_player1.char_type = final_player1.char_type.replace("\n", "")
final_player1.char_type is still 'Wizard\n'
I've also tried using strip() but I've been unsuccessful.
If anyone could help me with this I would greatly appreciate it. Sorry if I have overcomplicated this question but it's hard to articulate it without lots of info. Let me know if this is too much or if more info is needed to answer.
If '\n' is always at the end it may be best to use:
s = 'wizard\n'
s = s[:-1]
print(s, s)
Output:
wizard wizard
But I still think strip() is best:
s = 'wizard\n'
s = s.strip()
print(s, s)
Output:
wizard wizard
Normaly it should work with just
char_type = "Wizard\n"
char_type.replace("\n", "")
print(char_type)
The output will be "Wizard"

How to make a text file (name1:hobby1 name2:hobby2) into this (name1:hobby1, hobby2 name2:hobby1, hobby2)?

I'm new to programming and I need some help. I have a text file with lots of names and hobbies that looks something like this:
Jack:crafting
Peter:hiking
Wendy:gaming
Monica:tennis
Chris:origami
Sophie:sport
Monica:design
Some of the names and hobbies are repeated. I'm trying to make the program display something like this:
Jack: crafting, movies, yoga
Wendy: gaming, hiking, sport
This is my program so far, but the 4 lines from the end are incorrect.
def create_dictionary(file):
newlist = []
dict = {}
file = open("hobbies_database.txt", "r")
hobbies = file.readlines()
for rows in hobbies:
rows1 = rows.split(":")
k = rows1[0] # nimi
v = (rows1[1]).rstrip("\n") # hobi
dict = {k: v}
for k, v in dict.items():
if v in dict[k]:
In this case I would use defaultdict.
import sys
from collections import defaultdict
def create_dictionary(inputfile):
d = defaultdict(list)
for line in inputfile:
name, hobby = line.split(':', 1)
d[name].append(hobby.strip())
return d
with open(sys.argv[1]) as fp:
for name, hobbies in create_dictionary(fp).items():
print(name, ': ', sep='', end='')
print(*hobbies, sep=', ')
Your example give me this result:
Sophie: sport
Chris: origami
Peter: hiking
Jack: crafting
Wendy: gaming
Monica: tennis, design
you may try this one
data = map(lambda x:x.strip(), open('hobbies_database.txt'))
tmp = {}
for i in data:
k,v = i.strip().split(':')
if not tmp.get(k, []):
tmp[k] = []
tmp[k].append(v)
for k,v in tmp.iteritems():
print k, ':', ','.join(v)
output:
Monica : tennis,design
Jack : crafting
Wendy : gaming
Chris : origami
Sophie : sport
Peter : hiking
You could try something like this. I've deliberately rewritten this as I'm trying to show you how you would go about this in a more "Pythonic way". At least making use of the language a bit more.
For example, you can create arrays within dictionaries to represent the data more intuitively. It will then be easier to print the information out in the way you want.
def create_dictionary(file):
names = {} # create the dictionary to store your data
# using with statement ensures the file is closed properly
# even if there is an error thrown
with open("hobbies_database.txt", "r") as file:
# This reads the file one line at a time
# using readlines() loads the whole file into memory in one go
# This is far better for large data files that wont fit into memory
for row in file:
# strip() removes end of line characters and trailing white space
# split returns an array [] which can be unpacked direct to single variables
name, hobby = row.strip().split(":")
# this checks to see if 'name' has been seen before
# is there already an entry in the dictionary
if name not in names:
# if not, assign an empty array to the dictionary key 'name'
names[name] = []
# this adds the hobby seen in this line to the array
names[name].append(hobby)
# This iterates through all the keys in the dictionary
for name in names:
# using the string format function you can build up
# the output string and print it to the screen
# ",".join(array) will join all the elements of the array
# into a single string and place a comma between each
# set(array) creates a "list/array" of unique objects
# this means that if a hobby is added twice you will only see it once in the set
# names[name] is the list [] of hobby strings for that 'name'
print("{0}: {1}\n".format(name, ", ".join(set(names[name]))))
Hope this helps, and perhaps points you in the direction of a few more Python concepts. If you haven't been through the introductory tutorial yet... i'd definitely recommend it.

How to Turn contents of .txt file into a list and print random item from that list

No errors, but when I try to print a random item it will only print the last item of the .txt file every time.
How can I turn my text file into a list? More specifically how to turn the entire left side of a .split into a list?
Any insight you may have is welcomed!
My .txt file is formatted like so.
Ano Iyan? = What's That
Marunong ka bang mag-Ingles? = Do you know how to speak English?
May telepono ba dito? = is There a telephone here?
import hashlib
import random
testFile = ""
def qSearch():
options = input ("Vocab/Grammar/or Special? (v/g/s)")
if options == "v":
testFile = "Vocabtest"
Vocab()
elif options == "g":
Grammar()
testFile = "Grammartest"
elif options == "s":
Special()
testFile = "Specialtest"
else:
qSearch()
def Vocab():
with open('Vocabtest.txt','r') as f:
for line in f:
questions, answers = line.split("=")
print (random.choice([questions]))
qSearch()
(return in terminal)
Vocab/Grammar/or Special? (v/g/s)v
May telepono ba dito?
Your Vocab() function is reading all the data, but NOT saving that data in any significant or useful way. In the revised code below, we store all the question/answer pairs into a dictionary.
Having the data in a dictionary allows us to query the dictionary for a key to get the paired value.
Just prior to randomly choosing a key (using random.choice, we will convert the dict.keys() object to an indexable list.
def Vocab():
with open('Vocabtest.txt','r') as f:
q_and_a = dict() # creates a dictionary
for line in f:
question, answer = line.split("=")
q_and_a[question] = answer # stores the question and answer
keys = list(q_and_a.keys()) # create a list of keys
print(q_and_a[random.choice(keys)]) # randomly selects a key
# (question) and uses it to get
# an answer.

How can I create an average from a text file in Python 3.5.2?

I've been struggling with this for two days now and I can't seem to find any help. I need to search the file for a student ID (1001 is my test ID being used) and then add the numbers in each line that takes place below each occurrence of the student ID together in order to get an average.
filename = input("Enter file name: \n"
"Example: Grade Data.txt \n")
myFile = open(filename, "r")
selectSID = input("Enter SID: \n")
gradesNum = myFile.read().count(selectSID)
grades = myFile.read()
gradetotal = sum()
average = (gradetotal/gradesNum)
print(average)
The text file that is being opened looks like this:
1001
95
1002
99
1001
96
1002
0
1001
84
1002
25
1001
65
1002
19
This looks like homework so I don't want to write the code for you but here is a pseudo code (there are multiple ways to achieve what you want, this is just a simple beginner level code):
Open file to read
get two lines from the file
is the line1 interesting to me?
yes -> store value from line2 in an array
no -> ignore line2
close file
get average
Some useful references:
Python I/O
Powerful things in python to help with I/O
Built-in functions to help with basic operations like sum
from collections import defaultdict
# with open('filename') as f:
# file = [for i in f]
# in this case, it's the list below
file = [1001,95,1002,99,1001,96,1002,0,1001,84,1002,25,1001,65,1002,19]
infos = defaultdict(list)
sids = file[::2] # select sid info
grades = file[1::2] # select grade info
for sid,grade in zip(sids,grades):
infos[sid].append(grade)
print(infos[1001])
print(infos[1002])
out:
[95, 96, 84, 65]
[99, 0, 25, 19]
in this point, you can sum, average, max or min whatever you want.
Please don't use this code for your homework (use #Aditya's method); you need to learn the basics before using fancy libraries. However, I just learned about collections.defaultdict and I wanted to use it. Watch this video for a great demo on defaultdict.
import collections
import statistics
# This little guy will hold all of our grades
# https://youtu.be/lyDLAutA88s is a great video using it
grades = collections.defaultdict(list)
def get_next_num(file):
"""get the next line of a file,
remove any whitespace surrounding it,
and turn it into an integer"""
return int(next(file).strip())
with open('tmp.txt') as myfile:
while True:
try:
# seriously, watch the video
grades[get_next_num(myfile)].append(get_next_num(myfile))
except StopIteration: # end of file
break
student_id = int(input('Enter student ID. Choices: {} : '.format(list(grades.keys()))))
print(statistics.mean(grades[student_id]))
Updated Answer:
Okay, so I think I understand your question now... Same thing, except I suggest using a list, and as long as the file stays in the same format (SID, Score, so on...), this should work, and requires minimal understanding of Python (i.e No weird libraries like glob):
filename = input("Enter file name: \n"
"Example: Grade Data.txt \n")
myFile = open(filename, "r")
selectSID = input("Enter SID: \n")
raw = myFile.read() ## Raw contents of file.
val = raw.count( selectSID ) ## Returns number of occurences
print( "Occurrences: ", val ) ## Or do something else...
lines = raw.split("\n") ## Create a list containing each new line
scores = [] ## A list that will contain all your scores
while selectSID in lines:
val = lines.index( selectSID ) ## Returns where it is in the list,
score = lines[ val+1 ] ## Gets the item at that position (index) Because the score is one line after the SID
scores.append( int(score) ) ## Adds the score to the list. --Suggest you look into how to safely capturing "int"s (try, except, etc) so the program doesn't crash if the score isn't a number (Advance)
lines.remove( selectSID ) ## automatically removes first occurrence of the SID (cause that's the one we just used)
avg = sum(scores) / len(scores) ## sum() function is self explanatory (takes a list or tuple [a sequence] and adds all values (must be all numbers), THEN len() is just length.
This will return an integer, or with your file, will print:
Occurrences: 4
Regardless if this answered your question, my tip for learning basics is understanding file types and what they can do.
In your case, you will mainly need to focus on strings (text) and integers (whole numbers). Using Pythons IDLE, declare a variable, and type the name and a dot, and use tab to scroll through each functions available.
Example:
>>> myString = "Hello World"
>>> myString.[TAB] #--> [Context Menu Here]
Once you pick one form the list, enter an opening parenthesis "(", and it will give a brief description of what it does.
Hope that helps, and sorry for the lengthy reply (I was trying to explain and give pointers (tips) since you said you were a noob)

Categories