1

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

5
  • 6
    create a custom class that implements __getitem__ Commented Aug 15, 2019 at 21:14
  • 1
    @Just out of interest, what possible use does this have over just declaring the function? Commented Aug 15, 2019 at 21:35
  • @Jinglesting Good question! I'm creating a GUI that has a bunch of settings. Each setting has a lot of selectable options, with each option having a display-friendly version ("5 vertices") and an integer version (0x5) that's useful for the backend. I need a way to quickly convert from the backend version to the display version. Some settings are simple and have only four options. Others have 60,000 options, but the display value is predictable based on the backend value that gets passed in. With this, I can use dictionary syntax to convert all options without creating a 60,000 line dictionary. Commented Aug 15, 2019 at 22:58
  • hmmm, still confused. If you can pass the backend value into a dict lookup syntax, why can't you just pass it into a function? Commented Aug 20, 2019 at 15:14
  • @Jinglesting I've added an example of a use case to my answer. Hope that helps clarify things! Commented Aug 21, 2019 at 16:25

3 Answers 3

2

You could create it like this:

class my_dict_class:

    def __getitem__(self, key):
        if key == 0:
            return "Default"
        elif key == 1:
            return str(key) + " vertex"
        elif key <= 99999:
            return str(key) + " vertices"
        else:
            return "Ignore"

res = my_dict_class()

print(res[0]) # prints "Default"
Sign up to request clarification or add additional context in comments.

1 Comment

You win the race! Thanks for the help, this worked like a charm.
1

Creating a class with object.__getitem__(self, key) in a class will allow you to use that syntax:

class my_dict_class:

    def __getitem__(self, key):
        if key == 0:
            return "Default"
        elif key == 1:
            return str(key) + " vertex"
        elif key <= 99999:
            return str(key) + " vertices"
        else:
            return "Ignore"

my_dict = my_dict_class()
print(my_dict[0]) # Default
print(my_dict[1]) # 1 vertex
print(my_dict[55555]) # 55555 vertices
print(my_dict[99999]) # 99999 vertices
print(my_dict[3748293478932]) # Ignore

Edit: Too slow :p

Comments

0

Full code(based on your one):

class myDict(object): # if you want no inheritance at all(from dict).
    def __init__(this):
        pass;
    def __getitem__(this, key):
        if(not(isinstance(key, int))):
            raise Exception("TYPE KEY ERROR.");
        #END;
        if(key==0):
            return"DEFAULT";
        elif(key==1):
            return str(key)+" vertex";
        elif(key<=99999):
            return str(key) + " vertices";
        else:
            return str.__new__((str), "Ignore");
        #endif;
    #END;
#END;

my_dict = myDict();
print(my_dict[1]); # e.g.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.