Use a python dictionary for "switch" on datatype -


i’m trying write “switch” dictionary in python. want able read in data text file , different things depending on it’s datatype. example if read in string want compare string. or if read in float want operations it. it’s data cleaning operation machine learning program.

i if…else statement, since conceivably have every datatype, i’d rather cleaner.

i’m using following code:

varx = 2.0 switchdict = {"bool": "boolean", "int": "integer","float": "floattype",                "str": "string"}  switchdict[str(type(varx))]()  def boolean():     print("you have boolean" )  def integer():     print("you have integer")  def floattype():     print("you have float")  def string():     print("you have string”) 

it returns:

traceback (most recent call last):   file "/gower71/switch.py", line 5, in <module> switchdict[str(type(varx))]() keyerror: "<class ‘float'>" 

if change 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 not callable 

is there way switch on type this??

you should store actual function references values, instead of names strings. example -

def boolean():     print("you have boolean" )  def integer():     print("you have integer")  def floattype():     print("you have float")  def string():     print("you have string")  switchdict = {bool: boolean, int: integer, float: floattype, str: string} switchdict[type(varx)]() 

for need move construction of dictionary after functions defined.

also, recommended not use string name of function, conflicts string standard module. better use name, string_type or so.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -