Python3 pop() function only deleting strings - python-3.x

I am taking a beginners Python course and am currently creating this sample dictionary:
dictVar = {25:"The square root of 5","Vitthal":"SOME DUDE'S NAME",3.14:"Pi"}
The course is teaching how to use an interactive prompt to request the name of a Key in the dictionary which assigns it to the variable "inputKeyToDelete"
inputKeyToDelete = input("Please enter the key you wish to delete from the dictionary. Your key to delete is: ")
When I enter the key Vitthal the key-value pair is deleted, but when I enter the key 25 or 3.14 nothing occurs which is the cause for my question.
the instructor is using the following to perform the lookup\delete.
if inputKeyToDelete in dictVar:
dictVar.pop(inputKeyToDelete)
print("Ok, the key-value pair for Key '" + inputKeyToDelete + "' has been removed.")
Any tips is appreciated.

input always returns a string in python 3. "25" != 25 in python, so the key isn't found. You need to add code to deal with numeric keys. Here is one way:
inputKeyToDelete = input('enter a number:')
try:
inputKeyToDelete = eval(inputKeyToDelete)
except NameError:
pass
print (inputKeyToDelete)
print(type(inputKeyToDelete))
Or just change your example to only use string keys.
Note: In python 2, input would convert to integer for you, which might be confusing you a bit.

Replace your code with below line. Take user input and type cast to int because python takes string as a input.
inputKeyToDelete = int(input("Please enter the key you wish to delete from the dictionary. Your key to delete is: "))

Related

cant printing the value in the list in python after an if operator

I try to code a secret word prediction game. I have a list with 9 rows including the key words and the secret word. Secret word is in the first row. I wrote the code below but whatever I input as a "guess" it returns me "found the secret and the secret word (the first value of the list).
secret1 = open("keywordlist.txt", "r")
list1= (keywordlist.readlines())
gid=input("enter the game id: ")
if gid:=1:
print("category is", (list1[8]))
guess=input("guess the secret: ")
if guess := list1[0]:
print("found the secret", (list1[0]))
elif guess==list1[1]:
print("found a hint", (guess))
I wrote the code below but whatever I input as a "guess" it returns me "found the secret and the key word.
I want to do that my code check the input value and if it equals to first value of the list, it prints found the secret row.
If it equals to other values of the list, it prints the found a hint row.
There are a few errors in your code as well.
Firstly, it should be secret1.readlines()
if gid:=1: should be gid==1: because you are checking if it's equal to
You mentioned that you want to check if the input is the same as first element in list, this portion is correct but note the operator !=. Next, you want to print "found a hint" if it's NOT the same as first element BUT is within the list, so use elif guess in list:. If not in list at all, goes to else:
if guess != list1[0]:
print("found the secret", (list1[0]))
elif guess in list:
print("found a hint", (guess))
else:
print("not within the list")
Please note, because I don't have your keywordlist.txt, this only works if your list contain the EXACT keyword, and not a substring of the keyword. A different application is required if it isn't this condition.

making a dictionary of student from space separated single line user input where name will be key and list of exam numbers will be value

Suppose I take one line space separated input as by using a string as : john 100 89 90
now from this string a dictionary is to be made as : d={'john':[100,89,90]}. Here, the numbers are to be collected in a list as integers. Basically from that input string line I want to make a student info dictionary where the name will be the key and the numbers will be exam numbers collected in a list as integers.
st=input()
value=st[1:]
c=list(map(int, value.split()))
print(c)
key=st[0]
d={}
d[key]=c
print(d)
I was writing this but mistakenly written key=st[0].. but this will only take the first character j as name and rest as values so I eventually got error: invalid literal for int() with base 10: 'ohn'
So, how can I correct it and get the exact result that I mentioned above?? I also want to know alternative method for taking space separated input like john 100 89 90 other than strings.
Your approach is correct in a way , the only addition I would like to make is , have a preset delimiter string for student input info
student_dict = {}
loop_flag = True
loop_input = "Y"
delimit = "," #### You preset delimiter
while loop_flag:
key = input("Input Student Name : ")
if key in student_dict:
print("Student already in Dictionary, continuing...."
continue
else:
info_str = input("Input Student Information: ")
info_list = info_str.split(delimit)
student_dict[key] = info_list
loop_input = input("Do you wish to add another student (Y/N)"
if loop_input == "N":
loop_flag = False
You can even use the space delimiter as well , but a more intuitive delimiter is suggested

Returning the key to a randomly selected dictionary value

I have been asked to build a flashcard program with a dictionary provided giving the keys and values. The idea is to choose a letter to either view the key (word) or the value (definition of the word) and then when you press enter the value is provided to the key and vice versa.
I can randomly generate a key and show the value when hitting enter...
I can randomly generate a value but struggle to show the key when entering
#import the random module
from random import *
import csv
file = open('dictionary.txt', 'r')
#define a function for file_to_dictionary
def file_to_dictionary(filename):
"""return a dictionary with the contents of a file"""
file = open(filename, 'r')
reader = csv.reader(file)
dictionary = {}
for row in reader:
dictionary[row[0]] = row[1]
return dictionary
#set up the glossary
glossary = file_to_dictionary('dictionary.txt')
glossary.values()
#define a function to show a random flashcard
def show_flashcard(): #this is the function header
"""show the user a random key and ask them to define it.
Show the definition when the user presses return""" # the docstring
random_key = choice(list(glossary)) #obtain a random key by returning the glossary into a list of keys with list() and choice() for random
print('Define: ', random_key)
input ('Press return to see the definition')
print (glossary[random_key])
#define a function to show a random definition
def show_definition():
"""show a random value from the dictionary and ask them to name the word"""
random_value = choice(list(glossary.values()))
print ('What word relates to this definition ?', random_value)
input ('Press return to see the word')
print (glossary.values[random_value])
I get the required results from when I run the code for a random key and then pressing enter to see the value (definition) and also when I run the code for a random value, but then struggle in returning the key to match the value.
Below is the output of the code running correctly and returning an error:
Press s to see a flashcard, Press d to see definition, or press q to quit s
Define: container
Press return to see the definition
(As applied to computing) a cloud technology where the virtualisation happens within the operating system itself; a container is a portable module in which software can be run.
Press s to see a flashcard, Press d to see definition, or press q to quit d
What word relates to this definition ? Legible data unprotected by encryption.
Press return to see the word
Traceback (most recent call last):
File "/Users/degsy/Desktop/Python/tet_gloss.py", line 48, in <module>
show_definition()
File "/Users/degsy/Desktop/Python/tet_gloss.py", line 37, in show_definition
print (glossary.values[random_value])
TypeError: 'builtin_function_or_method' object is not subscriptable
You can have the same value for multiple keys. Getting the key from a value 1 for {1:1, 2:1, 3:1, 4:1} gives 4 possible keys for value of 1.
Probably easiest would be to take a random key,value tuple directly when asking and and ask about it:
from random import choice
def show_definition(d):
"""show a random value from the dictionary and ask them to name the word"""
# get a random key,value from .items()
random_key, random_value = choice(list(d.items()))
print ('What word relates to this definition ?', random_value)
input ('Press return to see the word')
print (random_key)
show_definition( {1:"one", 2:"two", 3:"three"} )
show_definition( {1:"one", 2:"two", 3:"three"} )
show_definition( {1:"one", 2:"two", 3:"three"} )
Output:
What word relates to this definition ? three
Press return to see the word
3
What word relates to this definition ? one
Press return to see the word
1
What word relates to this definition ? two
Press return to see the word
2
See dict.items()

Ask for input, stops asking when enter is pressed, then displays an alphabetically sorted list, print each item separately on a diff line

Challenge:
Need to write a program that asks the user to enter some data, for instance the names of their friends. When the user wants to stop providing inputs, he just presses Enter. The program then displays an alphabetically sorted list of the data items entered. Do not just print the list, but print each item separately, on a different line.
y = []
def alfabetisch( element ):
return element
while True:
user_input = input("Prompt: ")
if user_input != "":
y += [user_input]
if user_input == "":
break
for element in y:
y.sort( key= alfabetisch )
print( element )
I've made some changes and it works 'sometimes' now. If I put in the following input at the 'prompt:'
[Great, Amazing, Super, Sweet, Nice] it gives back: [Great, Great, Nice, Super, Sweet] so that is two times 'Great' and leaves out 'Amazing'
But when I give in the following input at the 'prompt:' [Amorf, Bread, Crest, Draft, Edith, Flood] it gives back: [Amorf, Bread, Crest, Draft, Edith, Flood], so with this particular input it does what I wanted it to do.
What am I doing wrong here, can anyone provide some pointers?
The input of a user is a string.
If the user doesn't input anything the output of input() function is '' ( as mentioned in the comments).
If the user inputs more than one item, as you mentioned for instance a list of friend names then iterating over the string will give you all the chars that compose that string.
A more Pythonic way of doing that will be:
user_input = input("Prompt: ")
print('\n'.join(sorted(user_input.split())))

Dictionary within a list - how to find values

I have a dictionary of around 4000 Latin words and their English meanings. I've opened it within Python and added it to a list and it looks something like this:
[{"rex":"king"},{"ego":"I"},{"a, ab":"away from"}...]
I want the user to be able to input the Latin word they're looking for and then the program prints out the English meaning. Any ideas as to how I do this?
You shouldn't put them in a list. You can use a main dictionary to hold all the items in one dictionary, then simply access to the relative meanings by indexing.
If you get the tiny dictionaries from an iterable object you can create your main_dict like following:
main_dict = {}
for dictionary in iterable_of_dict:
main_dict.update(dictionary)
word = None
while word != "exit"
word = input("Please enter your word (exit for exit): ")
print(main_dict.get(word, "Sorry your word doesn't exist in dictionary!"))
Well you could just cycle through your 4000 items...
listr = [{"rex":"king"},{"ego":"I"},{"a, ab":"away from"}]
out = "no match found"
get = input("input please ")
for c in range(0,len(listr)):
try:
out = listr[c][get]
break
except:
pass
print(out)
Maybe you should make the existing list into multiple lists alphabetically ordered to make the search shorter.
Also if the entry does not match exactly with the Latin word in the dictionary, then it won't find anything.

Resources