Mostly Linux & Python syntax notes and hyperlinks.

Tuesday, February 2, 2016

python: initialize a dictionary with input arguments key value key value etc


If you invoke scriptname with list of key names followed by their values.
e.g.
         python scriptname.py A 1 C 3 B 2

Then you could parse it like this:

dd={}

for i in range(1,len(argv),2):
    dd[sys.argv[i]]=sys.argv[i+1]

Toy code to test:

>>> params=['scriptname','A',1,'C',3,'B',2]
>>> dd={}
>>> for i in range(1,len(params),2):
...     dd[params[i]]=params[i+1]
...   
>>> dd
{'A': 1, 'C': 3, 'B': 2}

python: supply default values for incomplete dictionary



>>> default_dd={'A':1,'B':2,'C':3,'D':4,'E':5}
>>> dd={'B':2000,'D':4000}
>>> for key in default_dd.keys():
...     if not key in dd.keys():
...         dd[key]=default_dd[key]
...       
>>> dd
{'A': 1, 'C': 3, 'B': 2000, 'E': 5, 'D': 4000}
   
   


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.