I want to be able to call something like this:
def lookup(key):
if key == 0:
return "Default"
elif key == 1:
return str(key) + " vertex"
elif key <= 99999:
return str(key) + " vertices"
else:
return "Ignore"
using this syntax:
my_dict[key]
So essentially, I'd like to use dictionary syntax, but instead of actually looking up a real dictionary, I want to use conditionals to determine what the resulting of the key lookup should be, and return a value from there. It doesn't really matter what my_dict is, as long as it can be accessed like a dictionary can be.
I am aware that you can inherit the standard Python dict class, but I can't figure out if/how to use that ability to fulfill the above requirements.
Example Using Answer
Thanks for everyone's help! Here's the way in which I'm using this functionality:
A custom function with dictionary syntax:
class ComplexSetting:
def __getitem__(self, key):
if 0<=key<=10000:
return "Reserved " + hex(key)
elif 10001 <= key <= 60000:
return str(key*2)
else:
raise KeyError
Settings "dictionaries":
setting_1 = {
0: "option_0"
1: "option_1"
2: "option_2"
}
setting_2 = ComplexSetting()
A class that implements a generic setting:
class UserInterface:
def __init__(self, setting):
self.setting = setting
self.ask_for_input()
def ask_for_input(self):
value = input("Please select an option.")
# use generic setting dictionary to access result
result = self.setting[value]
# do some function with the result
print(result)
Now I can reuse the UserInterface class wherever I want to without having to worry about changing the way self.setting is used between implementations. This particular example is pretty useless, I'd imagine, but for my specific use case having this ability is quite helpful
__getitem__