Dictionary or If statements, Jython

I am writing a script at the moment that will grab certain information from HTML using dom4j.

Since Python/Jython does not have a native switch statement I decided to use a whole bunch of if statements that call the appropriate method, like below:

if type == 'extractTitle':
    extractTitle(dom)
if type == 'extractMetaTags':
    extractMetaTags(dom)

I will be adding more depending on what information I want to extract from the HTML and thought about taking the dictionary approach which I found elsewhere on this site, example below:

{
    'extractTitle':    extractTitle,
    'extractMetaTags': extractMetaTags
}[type](dom)

I know that each time I run the script the dictionary will be built, but at the same time if I were to use the if statements the script would have to check through all of them until it hits the correct one. What I am really wondering, which one performs better or is generally better practice to use?

Update: @Brian - Thanks for the great reply. I have a question, if any of the extract methods require more than one object, e.g.

handle_extractTag(self, dom, anotherObject)
# Do something

How would you make the appropriate changes to the handle method to implemented this? Hope you know what I mean :)

Cheers


Asked by: Maya709 | Posted: 24-09-2021






Answer 1

To avoid specifying the tag and handler in the dict, you could just use a handler class with methods named to match the type. Eg

class  MyHandler(object):
    def handle_extractTitle(self, dom):
        # do something

    def handle_extractMetaTags(self, dom):
        # do something

    def handle(self, type, dom):
        func = getattr(self, 'handle_%s' % type, None)
        if func is None:
            raise Exception("No handler for type %r" % type)
        return func(dom)

Usage:

 handler = MyHandler()
 handler.handle('extractTitle', dom)

Update:

When you have multiple arguments, just change the handle function to take those arguments and pass them through to the function. If you want to make it more generic (so you don't have to change both the handler functions and the handle method when you change the argument signature), you can use the *args and **kwargs syntax to pass through all received arguments. The handle method then becomes:

def handle(self, type, *args, **kwargs):
    func = getattr(self, 'handle_%s' % type, None)
    if func is None:
        raise Exception("No handler for type %r" % type)
    return func(*args, **kwargs)

Answered by: Alina969 | Posted: 25-10-2021



Answer 2

With your code you're running your functions all get called.

handlers = {
'extractTitle': extractTitle, 
'extractMetaTags': extractMetaTags
}

handlers[type](dom)

Would work like your original if code.

Answered by: Julia224 | Posted: 25-10-2021



Answer 3

It depends on how many if statements we're talking about; if it's a very small number, then it will be more efficient than using a dictionary.

However, as always, I strongly advice you to do whatever makes your code look cleaner until experience and profiling tell you that a specific block of code needs to be optimized.

Answered by: Chloe521 | Posted: 25-10-2021



Answer 4

Your use of the dictionary is not quite correct. In your implementation, all methods will be called and all the useless one discarded. What is usually done is more something like:

switch_dict = {'extractTitle': extractTitle, 
               'extractMetaTags': extractMetaTags}
switch_dict[type](dom)

And that way is facter and more extensible if you have a large (or variable) number of items.

Answered by: Marcus275 | Posted: 25-10-2021



Answer 5

The efficiency question is barely relevant. The dictionary lookup is done with a simple hashing technique, the if-statements have to be evaluated one at a time. Dictionaries tend to be quicker.

I suggest that you actually have polymorphic objects that do extractions from the DOM.

It's not clear how type gets set, but it sure looks like it might be a family of related objects, not a simple string.

class ExtractTitle( object ):
    def process( dom ):
        return something

class ExtractMetaTags( object ):
    def process( dom ):
        return something

Instead of setting type="extractTitle", you'd do this.

type= ExtractTitle() # or ExtractMetaTags() or ExtractWhatever()
type.process( dom )

Then, you wouldn't be building this particular dictionary or if-statement.

Answered by: John789 | Posted: 25-10-2021



Similar questions

Python - get object - Is dictionary or if statements faster?

I am making a POST to a python script, the POST has 2 parameters. Name and Location, and then it returns one string. My question is I am going to have 100's of these options, is it faster to do it in a dictionary like this: myDictionary = {"Name":{"Location":"result", "LocationB":"resultB"}, "Name2":{"Location2":"result2A", "Location2B":"result2B"}} And then I would use


python, dictionary and if statements

i have this code for renaming some files but when its the case that there are more than one file with the same name; the 'else' part doesn't even return the hello world TArchivo is the extention of the file: like ',jpg' and Numero is the number of strings that it will take from the name example: Onthedirectory: 'name.txt' def remove(3,'.txt') onthedirectory: 'e.txt' import os...


python - using dictionary instead of if statements

Closed. This question needs to be more focused. It ...


Python - get object - Is dictionary or if statements faster?

I am making a POST to a python script, the POST has 2 parameters. Name and Location, and then it returns one string. My question is I am going to have 100's of these options, is it faster to do it in a dictionary like this: myDictionary = {"Name":{"Location":"result", "LocationB":"resultB"}, "Name2":{"Location2":"result2A", "Location2B":"result2B"}} And then I would use


python, dictionary and if statements

i have this code for renaming some files but when its the case that there are more than one file with the same name; the 'else' part doesn't even return the hello world TArchivo is the extention of the file: like ',jpg' and Numero is the number of strings that it will take from the name example: Onthedirectory: 'name.txt' def remove(3,'.txt') onthedirectory: 'e.txt' import os...


python: dictionary and if statements

I have a file to read and a dictionary. If the file says: sort-by username I want the dictionary to be d = {'sort-by': 'username'} if the file says : sort-by name then I want the dictionary to be d = {'sort-by': 'name'} right now, I have: if 'user' in line: d['sort-by']...


python - Writing a dictionary to replace switch statements in functions

I've written a menu in Python 3 that takes user input, however to convert the string properly I've had to manually write out an if statement. I need to change this all to a dictionary to use across several different functions, storing variables in some and lists in another. So far the if statement looks like this. I've only pasted 'a', but 'b' is similar. while loop == 1: choice = menu() if choice =...


python - using dictionary instead of if statements

Closed. This question needs to be more focused. It ...


How do i replace values in a python dictionary without using long if else statements

This is list containing dictionary, the code block works I just want a more pythonic way of achieving this. The code checks if the condition is met and reassign a new value. for items in waytypes: if items['value'] == 1: items['value'] = 7 elif items['value'] == 2: items['value'] = 7 elif items['value'] == 3: items['value'] = 4 elif items[...


dictionary - PYTHON: IF Statements for DICT

i have a dict which contains data from my csv file: Standard rules1: Weight <= 1200 | Height <= 220 | Width <= 100 | Length <= 120 Standard rules2: Weight <= 750 | Height <= 120 | Width <= 100 | Length <= 120 | my dict: pwDa...


dataframe - Create dictionary from user input with if/then statements in Python

New Python learner here. I've looked all over for assistance but I can't seem to find a solution to my problem. I want to create a dictionary from user input, but for some of the variables, I would like to include if/then or while statements in order to skip questions that are irrelevant based on the user input. Here is an example of my code so far: input_dict = {'var1': input('Question 1:\n'), ...


Python: Using dictionary in place of if statements in a function that converts text numbers to digits

Basically what I want to do is to use a dictionary in place of a lot of if statements in this function which converts numbers in text to digits (e.g. 'one two two five' to 1225): def text_to_digit(s): temp = '' num = '' for i in s: if i == ' ': if temp == 'zero': num = num + '0' elif temp == 'one': num = num + '1' elif te...


python - How to create a dictionary using less if elif statements for a "dictionary"

In the program I'm revising, I'm making a calculator/dictionary of sorts. Ive refined the basis for each module, but now I'm stuck trying to figure out how exactly to go about setting it up so that it can actually take that input, then give you a value for what materials are needed to craft the item, and then calculate how many items you need to craft that item in bulk.


sorting - In Python, how can you easily retrieve sorted items from a dictionary?

Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key? For example, you had this: d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}


Python dictionary from an object's fields

Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this: >>> class Foo: ... bar = 'hello' ... baz = 'world' ... >>> f = Foo() >>> props(f) { 'bar' : 'hello', 'baz' : 'world' } NOTE: It should not include methods. Only fields.


python - How do you retrieve items from a dictionary in the order that they're inserted?

Is it possible to retrieve items from a Python dictionary in the order that they were inserted?


python - How can I make a dictionary from separate lists of keys and values?

I want to combine these: keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam'] Into a single dictionary: {'name': 'Monty', 'age': 42, 'food': 'spam'}


Is a Python dictionary an example of a hash table?

One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?


python - Is there a "one-liner" way to get a list of keys from a dictionary in sorted order?

The list sort() method is a modifier function that returns None. So if I want to iterate through all of the keys in a dictionary I cannot do: for k in somedictionary.keys().sort(): dosomething() Instead, I must: keys = somedictionary.keys() keys.sort() for k in keys: dosomething() Is there a pretty way to iterate t...


python - Interface to versioned dictionary

I have an versioned document store which I want to access through an dict like interface. Common usage is to access the latest revision (get, set, del), but one should be able to access specific revisions too (keys are always str/unicode or int). from UserDict import DictMixin class VDict(DictMixin): def __getitem__(self, key): if isinstance(key, tuple): docid, rev = key e...


python - List all words in a dictionary that start with <user input>

How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! Edit: I'm using python, but I assume that this is a fairly language-independent problem.


python - Check if a given key already exists in a dictionary and increment it

How do I find out if a key in a dictionary has already been set to a non-None value? I want to increment the value if there's already one there, or set it to 1 otherwise: my_dict = {} if my_dict[key] is not None: my_dict[key] = 1 else: my_dict[key] += 1


Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?

I have a list of variable names, like this: ['foo', 'bar', 'baz'] (I originally asked how I convert a list of variables. See Greg Hewgill's answer below.) How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values of the variables? {'foo': foo, 'bar': bar, 'baz': baz} Now that I'm re-aski...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top