Enter value to produce keys in dictionary [Python] [duplicate] - python

This question already has answers here:
Reverse / invert a dictionary mapping
(32 answers)
Closed 6 years ago.
I have made my own Morse Code translator where you can enter the code and the corresponding letter prints out. However, what I want to do is that whenever I enter a letter, the code prints out. Here's my code:
MorseCode = {'.-':'A',
'-...':'B',
'-.-.':'C',
'-..':'D',
'.':'E',
'..-.':'F',
'--.':'G',
'....':'H',
'..':'I',
'.---':'J',
'-.-':'K',
'.-..':'L',
'--':'M',
'-.':'N',
'---':'O',
'.--.':'P',
'--.-':'Q',
'.-.':'R',
'...':'S',
'-':'T',
'..-':'U',
'...-':'V',
'.--':'W',
'-..-':'X',
'-.--':'Y',
'--..':'Z',
'.----':1,
'..---':2,
'...--':3,
'....-':4,
'.....':5,
'-....':6,
'--...':7,
'---..':8,
'----.':9,
'-----':0
}
print "Type 'help' for the morse code."
print "Type 'end' to exit the program.\n"
while True:
code = raw_input("Enter code:")
if code in MorseCode:
print MorseCode[code]
So the question is: Is there a way to somehow invert this dictionary so whenever I enter 'A', '.-' will print out? I'm only studying python for two weeks now so I'm still mastering the basics before I move on to the more advanced levels. Thank you!

You can use dictionary comprehension (assuming you are using Python 2.6+) to easily create a new, inverted dictionary:
letters_to_morse = {char: code for code, char in MorseCode.items()}
letters_to_morse['A']
>> '.-'

Related

I am trying to create a calculator program

I am writing a code that removes '√' symbol from a string and get's the index of it, By using the 'enumerate' function in python, I have already made an functioning calculator but I am improving it.
Code:
cal = input(">>> ")
for i, c in enumerate(cal):
if c == '√':
cal = cal[0:i]+cal[i+1:]
print(cal)
Input:
>>> 123√456√789√123
Output:
123456√89√13
I am not getting the right output when I remove a character from the string the enumerate function messes up the index , So I can't figure it out.
[My first time using stackover flow Don't judge]
As per the comments. You have made the classic error of editing a list whilst looping thru it. The edits will change the list, so the positions will be incorrect.
a good solution is this:
cal = '123√456√789√123'
cal = cal.replace('√','')
cal
Which returns this:
'123456789123'

code does not work in sublime text when using function with "return" statement [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 11 months ago.
I'm new to python programming, and as a beginner I want to start by using a code editor,
I choose sublime text 4 but I face this problem,
So help me please !
This is the code :
def return_string(your_string):
if len(your_string) >= 4:
new_string = your_string[0:2] + your_string[-2:]
return new_string
elif len(your_string) == 2:
new_string = your_string * 2
return new_string
elif len(your_string) < 2:
new_string = ""
return new_string
return_string("welcome")**
the expected output is "weme" but I get nothing in sublime text output (when I click Ctrl + B).
When I change return to print the code is executed properly.
By the way the code above works in vscode without any problem.
Python doesn't print outside the REPL normally, unless you explicitly tell it to. Add a call to print on your last line:
print(return_string('welcome'))
This is why adding an explicit print in your function works.
You can store the value into a variable first if you want to use it elsewhere:
result = return_string('welcome')
print(result)
Because "return string" returns a string, you must first save the data in a variable, which you may then use later in the program.
result_string = return_string("welcome")
print(result_string)

How to ask the user again if he wants to remove more links in my python code [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
Hi I have a python code which does the following things sequentially
Displays a list of urls
asks the user if they want to remove
any links.
If the user inputs yes then takes an input which link
to remove and removes the link
code exits.
My issue is I want the code to ask the user again after removing the link if they want to remove more links?
Can someone help me figure it out. Sorry I am new to python so if this question seems very trivial.
My code:
import sys
def remove_links():
# initializing list
list = links
# initializing string
str_to_remove = input("Enter the link you want to remove: ")
# Remove List elements containing String character
# Using list comprehension
links.remove(str_to_remove)
# printing result
print("The list after removal : " + str(links))
print(len(links))
# printing original list
print("The list of links are : " + str(links))
print(len(links))
# Sets to simplify if/else in determining correct answers.
yesChoice = ['yes', 'y']
noChoice = ['no', 'n']
# Convert their input to lowercase.
choice = input("Do you want to remove some/any links? (y/N) ").lower()
if choice in yesChoice:
remove_links()
elif choice in noChoice:
# exit the code
sys.exit("User doesn't want to make any modifications.")
else:
# print("Invalid input.\nExiting.")
sys.exit("Invalid input.\nExiting.")
You can put it in while loop, like this and reaplace sys.exit() to break:
while True:
choice = input("Do you want to remove some/any links? (y/N)").lower()
if choice in yesChoice:
remove_links()
elif choice in noChoice:
print("User doesn't want to make any modifications.")
break
else:
print("Invalid input.\nExiting.")
break
This is only one way to do this

How to catch a character from keyboard [duplicate]

This question already has answers here:
How to read keyboard input?
(5 answers)
Closed 6 years ago.
I am working on a python project and I have got the following questions.
How to catch a character in python ? What modules I need to use ? What functions I need to use?
If you need to take a line of input just use:
x = input('Your name: ')
y = input()
Or (For Python 2)
x = raw_input('Your name: ')
y = raw_input()
For taking just one character from the keyboard you can use msvcrt.getch():
import msvcrt
key = msvcrt.getch()
if key == 'a':
print("You pressed a")

Python - CSV Reading with dictionary [duplicate]

This question already has answers here:
TypeError: 'dict_keys' object does not support indexing
(5 answers)
Closed 7 years ago.
So,
I am using Python 3.4.2 and I have this code:
import csv
import random
filename = input("Please enter the name of your file: ")
# Open file and read rows 0 and 1 into dictionary.
capital_of = dict(csv.reader(open(filename)))
# Randomly select a country from the dictionary
choice = random.choice(capital_of.keys())
# The correct capital corresponds to the dictionary entry for the country
answer = capital_of[choice]
# Take a guess from the user
guess = input("What is the capital of %s? " % choice)
# If it's right, let the user know
if guess == answer:
print("Right-o!")
# Otherwise, do what you want to do.
This code was given to me as a solution on a previous question but upon entering the name of my CSV file, I get this error:
TypeError: 'dict_keys' object does not support indexing
Does anybody know a fix for this?
Thanks
Try this:
choice = random.choice(list(capital_of.keys()))

Categories