Mostly Linux & Python syntax notes and hyperlinks.

Tuesday, February 2, 2016

python: initialize a dictionary with uncertain number of input values

If you know the order of the expected input parameters, but you don't know how many will be supplied:


if __name__ == "__main__":
    #initialize list of expected parameters, in order
    dd_parameters=['scriptname','A','B','C','D','E']
    dd={} 
    if len(sys.argv) > 1: 
        #loop through the actual input parameters
        for i in range(1, len(sys.argv)):
            dd[dd_parameters[i]]=sys.argv[i]

See, you automatically stop at the end of the number of input parameters.
Here's some toy code to test the logic:

 >>> std_parms=['scriptname','A','B','C','D']
 >>> input_parms=['scriptname','A_Value','B_Value']
 >>> dd={}
 >>> for i in range(1,len(input_parms)):
 ...     dd[std_parms[i]]=input_parms[i]
 ...
 >>> dd
 {'A': 'A_Value', 'B': 'B_Value'} 

After that, you may want to fill in the default values for the parameters not supplied.

No comments:

Post a Comment