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}

No comments:

Post a Comment