This function creates a dictionary containing all of the variables passed as parameters with the variable name being the key and the value of the variable as the value. I use it frequently when passing parameters to another function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
from traceback import extract_stack def makeDict(*args): strAllStack = str(extract_stack()) intNumLevels = len( extract_stack() ) intLevel = 0 blnFinished = False while not blnFinished: strStack = str( extract_stack()[intLevel] ) if strStack.find( "makeDict( ")>0: blnFinished = True intLevel += 1 if intLevel >= intNumLevels: blnFinished = True strStartText = "= makeDict( " intLen = len( strStartText ) intOpenParenLoc = strStack.find( strStartText ) intCloseParenLoc = strStack.find(")", intOpenParenLoc ) strArgs = strStack[ intOpenParenLoc+intLen : intCloseParenLoc ].strip() lstVarNames = strArgs.split(",") lstVarNames = [ s.strip() for s in lstVarNames ] if len( lstVarNames ) == len( args ): tplArgs = map( None, lstVarNames, args ) newDict = dict( tplArgs ) return newDict else: print "Error. makeDict Failed." return None
I created this function because I found the syntax for creating dictionaries a little cumbersome when all I wanted to do was quickly pack up a bunch of variables into a dictionary and then pass the newly created dictionary as a single parameter to various functions. It also allows you to add or subtract elements to the dictionary without having to worry about finding and changing the function definition and then all of the places where that function is called.