I am trying to have a user input a 1,2,3,4,5,6.
Then have that integer align with a character name in my dictionary.
characters = {
'Stark': '1',
'Greyjoy': '2',
'California': '3',
'Whitewalkers': '4',
'Knights Watch': '5',
'Dalthraki': '6'
}
print 'Type 1 for Stark'
print 'Type 2 for Greyjoy'
print 'Type 3 for Lannister'
print 'Type 4 for Whitewalkers'
print 'Type 5 for Knights Watch'
print 'Type 6 for Dalthraki'
choice = raw_input("> ")
if choice in characters:
print 'You\'ve selected', choice
else:
splash()
I want to have my script print "You've selected Stark" after having the user input a 1.
Thanks for your help
You have the dict backwards:
characters = {
'1': 'Stark',
'2': 'Greyjoy',
'3': 'California',
'4': 'Whitewalkers',
'5': 'Knights Watch',
'6': 'Dalthraki',
}
print 'Type 1 for Stark'
print 'Type 2 for Greyjoy'
print 'Type 3 for Lannister'
print 'Type 4 for Whitewalkers'
print 'Type 5 for Knights Watch'
print 'Type 6 for Dalthraki'
choice = raw_input("> ")
if choice in characters:
print 'You\'ve selected', characters[choice]
else:
pass
change your dict to :
characters = {
'1':'Stark',
'2':'Greyjoy',
'3':'California',
'4':'Whitewalkers',
'5':'Knights Watch',
'6':'Dalthraki'
}
and use:
if choice in characters:
print 'You\'ve selected {0}'.format(characters[choice])
else:
splash()
You can't really use a dictionary that way. You can reverse the key/value pairs and then use characters[choice] to get the name of the character. If you want to preserve the dictionary as is, your best bet is to iterate over the items
characterName = None
names = characters.items()
while characterName is None and names:
if names[0][1] == choice:
characterName = names[0][0]
else:
names = names[1:]
After running this, you'll either have a character name in characterName, or it will be None if the user made an invalid entry.
Related
I want to create a dictionary that has keys and values, values has to be 3 elements long list. the first is a string that asks for input, the second a function that check a condition and the third a string to print if the condition is false
dict = {
'input 1': ['number > 10', def check(n): pass if n > 10 else raise ValueError, 'the number must be gratere than 10'],
'input 2': ['3 words', def check(text): pass if len(text) == 3 else raise ValueError, 'must be 3 words'],
'input 3': ['name', def check(text, name_list): pass if text in name_list else raise ValueError, 'the name has to be one of them '.format(x = name_list)]
}
for i in dict:
while True:
text = input(dict[i][0])
try:
dict[i][1](text)
break
except ValueError:
print(dict[i][2])
I know this is very strange but the dict is very long and with very different conditions.
I don't even know how can I pass multiple arguments to the funcs that need more than one
This does what you ask. Take some time to note the changes I've made here.
Note that the functions must all accept the same parameters.
def check_num( val ):
n = int(val )
if n <= 10:
raise ValueError( 'the number must be greater than 10' )
def check_3( val ):
if len(val.split()) != 3:
raise ValueError( 'must be 3 words' )
def check_name( val ):
if text not in name_list:
raise ValueError( 'the name must e one of' + (' '.join(name_list)) )
data = {
'input 1': ['Enter number', check_num],
'input 2': ['Enter 3 words', check_3],
'input 3': ['Enter a name', check_name]
}
name_list = ['Bill', 'Ted', 'Tom']
for i,info in data.items():
while True:
text = input(info[0]+': ')
try:
info[1](text)
break
except ValueError as e:
print( e )
If all your functions take only the input text as argument, make your function return a bool value:
dict = {
'input 1': ['number > 10', lambda n: n > 10, 'the number must be gratere than 10'],
'input 2': ['3 words', lambda text:len(text) == 3, 'must be 3 words'],
'input 3': ['name', lambda text: text in name_list, 'the name has to be one of them '.format(x = name_list)]
}
for i in dict:
while True:
text = input(dict[i][0])
res = dict[i][1](text)
if res:
break
else:
print(dict[i][2])
There is no easy way to make your third function work, because it requires a different number of arguments, I suggest setting name_list as a global variable.
Use lambda to create function expressions in the list, not def. But lambda can only contain a single expression to evaluate and return; pass and raise are statements, not expressions.
So you'll need to define these functions outside the dictionary, then reference them there.
And since you never use the dictionary keys, iterate over the values().
Don't use dict as a variable name, it overwrites the built-in class with that name.
name_list will need to be a global variable. All the check functions can only take 1 argument, since the loop has no way of knowing that some functions require additional arguments. It just passes the input text.
def check_greater_10(n):
if n <= 10:
raise ValueError
def check_3_words(text):
if len(text.split()) != 3:
raise ValueError
def check_name_list(text):
if text not in name_list:
raise ValueError
mydict = {
'input 1': ['number > 10', check_greater_10, 'the number must be greater than 10'],
'input 2': ['3 words', check_3_words, 'must be 3 words'],
'input 3': ['name', check_name_list, 'the name has to be one of them: {x} '.format(x = name_list)]
}
for prompt, check, error in mydict.values():
while True:
text = input(prompt)
try:
prompt(text)
break
except ValueError:
print(error)
get input using realdlines() function:
import sys
inputx = sys. stdin. readline()
print(inputx)
for no of lines use sys.stdin.readlines() but it must be given under for loop with range
This question already has answers here:
Python list of dictionaries search
(24 answers)
Closed 2 years ago.
I want to know If there is anyway when someone enters, let's say '070718604545'. It Looks it up and if it's there it prints others in the list, Example below
Patt = [
{'Phone': "0718604545", 'Name': "Tom", 'Age': '2007'}
{'Phone': "0718123567", 'Name': "Katy", 'Age': '1998'}
{'Phone': "0718604578", 'Name': "BillyW", 'Age': '1970'}
....
....
....
....
{'Phone': "0714565778", 'Name': "Sony", 'Age': '1973'}
]
He will enter '0718604545' as exmaple.
x = input("Enter Phone")
Search for x in Patt[Phone]:
name = Patt[Name] where Phone = x
print(name)
So the answer should be Tom.
Thanks,
You can get the number by iterating over the list patt and then acess each phone key in patt's items and use the == operator to compare with the phone number you are loooking for. The function below does the job.
def answer(search):
for data in patt: # iterate over each item in patt
if data["Phone"] == search: # compare the current value if it is the searched one
return data["Name"] # return the name in the dictionary when the number is found
return None # if it is not found, return None
print(answer('0718604545'))
Below should work. For every item, check if 'phone' key has value matching x. IF yes, then return the value of 'name' key.
x = input("Enter Phone")
for item in Patt:
if item["Phone"] == x:
print(item["Name"])
while preparing answer, I did not notice that one correct answer was already posted and accepted. Though, posting my version of the answer below with added feature of continuous questioning and an ability to exit from the program.
Patt = [
{'Phone': "0718604545", 'Name': "Tom", 'Age': '2007'},
{'Phone': "0718123567", 'Name': "Katy", 'Age': '1998'},
{'Phone': "0718604578", 'Name': "BillyW", 'Age': '1970'},
{'Phone': "0714565778", 'Name': "Sony", 'Age': '1973'}
]
print(Patt)
def search_phone_records(user_phone):
for record in Patt: # Iterate over all the phone records in the dictionary
if user_phone == record['Phone']: # stop if found phone number in the dictionary
return record['Name'] # Return user's name from the phone record
return None
while True:
user_input = input("Enter Phone or press 'x' to exit: ")
if user_input in ('x', 'X'):
print("Have a nice day!!! Thank you using our service!!!")
break # End the programme
# Search for the phone number
user_name = search_phone_records(user_input)
#print("[{0}]".format(user_name))
if type(user_name) == type(None): # Phone number is not found
print("Oops!!! Entered phone number ({0}) is not found in the dictionary!!!".format(user_input))
else: # Phone number is found
print("Entered phone number ({0}) is found in the dictionary!!!".format(user_input))
print("It is {1}'s phone number.".format(user_input, user_name))
Another solution using dictionary comprehension:
Patt = [
{'Phone': "0718604545", 'Name': "Tom", 'Age': '2007'},
{'Phone': "0718123567", 'Name': "Katy", 'Age': '1998'},
{'Phone': "0718604578", 'Name': "BillyW", 'Age': '1970'},
{'Phone': "0714565778", 'Name': "Sony", 'Age': '1973'}
]
print(Patt)
def search_phone_records_using_dictionary_comprehension(user_phone):
return {'Name': record['Name'] for record in Patt if user_phone == record['Phone']}
while True:
user_input = input("Enter Phone or press 'x' to exit: ")
if user_input in ('x', 'X'):
print("Have a nice day!!! Thank you using our service!!!")
break # End the programme
result = search_phone_records_using_dictionary_comprehension(user_input)
print("result = {0}".format(result))
if len(result) == 0: # Phone number is not found
print("Oops!!! Entered phone number ({0}) is not found in the dictionary!!!".format(user_input))
else: # Phone number is found
print("Entered phone number ({0}) is found in the dictionary!!!".format(user_input))
print("It is {1}'s phone number.".format(user_input, result['Name']))
I have a dataframe that one of its columns called proj has a sentence in every row and in that sentence a name of a city is mentioned. I want to do an if condition that when a password is being passed a different city's data will be available.
proj
sd_32 New York
eo_31 Lisbon
..
Ex.
x = pd.read_csv(r'C:\Users\user\Desktop\Dataset.csv', sep = ',')
while True:
passw = input('Password').upper()
if not passw in ('A','B'):
print('Try again')
continue
else:
break
if passw == 'A':
df = x[x['proj'].str.contains('New York')]
print(df)
elif passw == 'B':
df = x[x['proj'].str.contains('Lisbon')]
print(df)
How to do this in a more Pythonic way?
I thought about making a list :
city = ['New York','Lisbon','Berlin',..] #unique names of cities
and then pass this in a code that for every individual city, depending the password does an if process like I did but with this idea. How can I proceed with this?
Perhaps use a dict with passwords as key, and city names as values: cities = {'A': 'New York', 'B': 'Lisbon', ...}. Admittedly, you still have to check for valid keys, but that happens in the loop above, when asking for the input password (using the dict keys):
cities = {'A': 'New York', 'B': 'Lisbon'}
x = pd.read_csv(r'C:\Users\user\Desktop\Dataset.csv', sep = ',')
while True:
passw = input('Password').upper()
if passw not in cities: # `in cities` same as `in cities.keys()`
print('Try again')
continue
else:
break
df = x[x['proj'].str.contains(cities[passw])]
print(df)
You can use a dict in your case
Ex:
d = {"A": 'New York', "B": 'Lisbon'}
if passw in d:
df = x[x['proj'].str.contains(d[passw])]
What I'm trying to do with my program is to ask a user to enter a input string that will later be converted to uppercase or lowercase using str.upper or str.lower.
I have 5 sets options that the user can chose:
a = 'convert to upper case'
b = 'convert to lower case'
c = 'switch case of every alphabetic character to the opposite case'
d = 'convert first and last chrs of each word to upper case, and others to lower'
e = 'no change'
So far I have done the conversion for options a and b. But before I move forward creating a code for options c, d and e. I'm trying to create a loop but I'm not sure how to do it using raw_input and strings.
This is the code that I have so far:
# Conversion Rules
a = 'convert to upper case'
b = 'convert to lower case'
c = 'switch case of every alphabetic character to the opposite case'
d = 'convert first and last chrs of each word to upper case, and others to lower'
e = 'no change'
def upper():
print 'Your Input: %s' % choice
print 'Choosen Conversion Rule: %s' % a
return 'Conversion Result: %s' % option_A
def lower():
print 'Your Input: %s' % choice
print 'Choosen Conversion Rule: %s' % b
return 'Conversion Result: %s' % option_B
choice = str(raw_input('Choose an Option:'))
if (choice == 'A') or (choice == 'a'):
value_A = str(raw_input('Enter a String to Convert:'))
option_A = str.upper(Value_A)
print upper()
elif (choice == 'B') or ('b'):
value_B = str(raw_input('Enter a String to Convert:'))
option_B = str.lower(value_B)
print lower()
else:
print 'Goodbye' # Here I want to break if 'Q' is entered if 'Q' is entered.
So after the user enters an option. For example 'A' or 'a'. The first condition will run but then I want to add a loop that goes back to the beginning of the code and allows the user to enter the option again or choose a different option so a different condition will run.
choice = str(raw_input('Choose an Option:'))
if (choice == 'A') or (choice == 'a'):
value_A = str(raw_input('Enter a String to Convert:'))
option_A = str.upper(Value_A)
print upper()
# I want to add a loop here to go back to the 'choice' variable.
You can put all of your user-interface inside a while loop that loops forever (until for example some key is presses).
# Conversion Rules
a = 'convert to upper case'
b = 'convert to lower case'
c = 'switch case of every alphabetic character to the opposite case'
d = 'convert first and last chrs of each word to upper case, and others to lower'
e = 'no change'
def upper():
print 'Your Input: %s' % choice
print 'Choosen Conversion Rule: %s' % a
return 'Conversion Result: %s' % option_A
def lower():
print 'Your Input: %s' % choice
print 'Choosen Conversion Rule: %s' % b
return 'Conversion Result: %s' % option_B
while True:
choice = str(raw_input('Choose an Option:'))
if (choice == 'A') or (choice == 'a'):
value_A = str(raw_input('Enter a String to Convert:'))
option_A = str.upper(Value_A)
print upper()
elif (choice == 'B') or ('b'):
value_B = str(raw_input('Enter a String to Convert:'))
option_B = str.lower(value_B)
print lower()
else:
print 'Goodbye' # Here I want to break if 'Q' is entered if 'Q' is entered.
break
Note that the "break" is what breaks you out of the loop. Since the user-interface part is in the while loop, it will repeat.
I have the following code:
people = {'Bob' : {'phone' : '12',
'birthday' : 'May',
'address' : 'ABC',
'interests' : ['a', 'b', 'c']},
'Mary' : {'phone' : '13',
'birthday' : 'April',
'address' : 'CBA',
'interests' : ['d', 'e', 'f']},
response = ['']
wrong = "I don't know. Try again or type 'quit' to get out: "
while response[0] != 'quit':
response = raw_input("Please enter who you're looking for, or type 'quit' to get out: ").split()
try:
print "%s's %s is %s" % (response[0], response[1], people[response[0]][response[1]])
except KeyError:
print wrong,
I'd like to make it so the input can be in any case and still generate the correct output.
E.g.
'Mary phone', 'mary Phone', 'MARY PHONE'
all give
Mary's phone number is 13.
You should use capitalize() and lower()
while response[0] != 'quit':
response = raw_input("Please enter who you're looking for, or type 'exit' to quit the program: ").split()
try:
print "%s's %s is %s" % (response[0].capitalize(), response[1].lower(), people[response[0].capitalize()][response[1].lower()])
except KeyError:
print wrong,
You should change the 'bob' key to 'Bob', if you go this route...
Alternatively, you can save a few more CPU cycles if you reuse results, as mentioned by rubik below.
while response[0] != 'quit':
response = raw_input("Please enter who you're looking for, or type 'exit' to quit the program: ").split()
try:
fn, thing = response[0].capitalize(), response[1].lower()
print "%s's %s is %s" % (fn, thing, people[fn][thing])
except KeyError:
print wrong,
Try making sure the input is always lowercase by converting it to lowercase with str.lower(). Then make sure all of your people{} names are lowercase as well for easy searching, and format the output back to a capitalized name when you do the output.