Vermillion Vermillion - 21 days ago 5
Python Question

Converting an if/else block with True/False statements into a dictionary

I am iterating through characters in a string, and I want to determine the type of each character.

This can be done with an if/else block:

if char.isdigit():
char_type = 'number'
elif char.isalpha():
char_type = 'letter'
elif char in {'*', '/', '+', '-', '='}:
char_type = 'operator'
else:
char_type = 'other'


If the code was something like this:

if val == 1:
char_type = 'number'
elif val == 2:
char_type = 'letter'
elif val == 3:
char_type = 'operator'


The dictionary could be:

d = {1: 'number', 2: 'letter', 3: 'operator'}


But in this case, each of the statements is either
True
or
False
. Can this be converted into a dictionary?

Answer

Yes, you can use the d[char] syntax, but it hardly sees worth the cost in complexity and readability.

You could encapsulate your if/else in the __getitem__ method of a class, and then use [] syntax to retrieve the character type, like so:

class CharType:
    def __getitem__(self, char):
        if char.isdigit():
            char_type = 'number'
        elif char.isalpha():
            char_type = 'letter'
        elif char in {'*', '/', '+', '-', '='}:
            char_type = 'operator'
        else:
            char_type = 'other'
        return char_type

d = CharType()

print(d["a"], d["+"])