Reputation: 31
I want to create a function that returns the key if the user entered the value and the value if the user entered the key
I wrote this code, but is there a way to do this using dictionary?
def select(word):
if word == 'Hello':
return 'Hola'
elif word == 'Hola':
return 'Hello'
Upvotes: 0
Views: 181
Reputation: 241
def get_key_value(kv, my_dict): # kv stands for key/value, since you don't know if it's key or value.
# tries to get a value from the dictionary using the kv key.
# if kv really is a key, my_dict.get(kv) will return the value, otherwise it will return None.
# so, then we know kv isn't a key in the dictionary.
if my_dict.get(kv):
return my_dict.get(kv)
# so, maybe kv is a value.
# if kv is in my_dict.values() we then find what's its key using loop.
elif kv in my_dict.values():
for item in my_dict.items():
if item[1] == kv:
return item[0] # item[0] is the key for the value kv.
Upvotes: 0
Reputation: 2147
Just fill your dictionary with lowercase terms. It will return a capitalized word if you use one.
#! /usr/bin/env python3
dictionary = { 'hello':'hola', 'one':'uno', 'two': 'dos' }
def select( word ):
lowercase = word .lower() ## just test for lowercase values, easier
caps = word[0] .isupper() ## check if first letter caliptalized
for English, Spanish in dictionary .items():
if lowercase == English:
if caps: return Spanish[0] .upper() +Spanish[1:] ## Hola
else: return Spanish ## hola
elif lowercase == Spanish:
if caps: return English[0] .upper() +English[1:] ## Hello
else: return English ## hello
print( select( 'Hola' ) )
Hello
Upvotes: 1