Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a python dictionary for "switch" on datatype

I’m trying to write a “switch” dictionary in python. I want to be able to read in data from a text file and do different things depending on it’s datatype. So for example if I read in a string I want to compare it to another string. Or if I read in a float I want to do some operations with it. It’s a data cleaning operation for a machine learning program.

I could probably do this with an If…Else statement, but since I could conceivably have something for every datatype, I’d rather do it cleaner.

I’m using the following code:

varX = 2.0
switchDict = {"bool": "boolean", "int": "integer","float": "floatType",
               "str": "string"}

switchDict[str(type(varX))]()

def boolean():
    print("You have a boolean" )

def integer():
    print("You have an integer")

def floatType():
    print("You have a float")

def string():
    print("You have a string”)

It returns:

Traceback (most recent call last):
  File "/Gower71/Switch.py", line 5, in <module>
switchDict[str(type(varX))]()
KeyError: "<class ‘float'>"

If I change the switchDict lines to:

switchDict = {bool: "boolean", int: "integer", float: "floatType", str: "string"}
switchDict[type(varX)]()

It returns:

Traceback (most recent call last):
  File "/Gower71/Switch.py", line 5, in <module>
    switchDict[type(varX)]()
TypeError: 'str' object is not callable

Is there a way to switch on type like this??

like image 830
Joe Smith Avatar asked Sep 17 '25 12:09

Joe Smith


1 Answers

You should store the actual function references as values, instead of their names as strings. Example -

def boolean():
    print("You have a boolean" )

def integer():
    print("You have an integer")

def floatType():
    print("You have a float")

def string():
    print("You have a string")

switchDict = {bool: boolean, int: integer, float: floatType, str: string}
switchDict[type(varX)]()

For this you would need to move the construction of the dictionary to after all the functions are defined.

Also, it would be recommended to not use string as the name of a function, it conflicts with string which is a standard module. It would be better to use another name, like string_type or so.

like image 159
Anand S Kumar Avatar answered Sep 19 '25 07:09

Anand S Kumar