Skip to content
Related Articles

Related Articles

Improve Article

Python: Key Value pair using argparse

  • Last Updated : 28 Jul, 2020
Geek Week

The argparse module in Python helps create a program in a command-line-environment in a way that appears not only easy to code but also improves interaction. It also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

Steps For Using Argparse Module: 

  1. Creating a Parser: Importing argparse module is the first way of dealing with the concept. After you’ve imported it you have to create a parser or an ArgumentParser object that will store all the necessary information that has to be passed from the python command-line.
  2. Adding Arguments: Next step is to fill the ArgumentParser with information about the arguments of the program. This implies a call to the add_argument() method. These informations tell ArgumentParser how to take arguments from the command-line and turn them into objects.
  3. Parsing Arguments: The information gathered in step 2 is stored and used when arguments are parsed through parse_args(). The data is initially stored in sys.argv array in a string format. Calling parse_args() with the command-line data first converts them into the required data type and then invokes the appropriate action to produce a result.

Key-Value Pair Using Argparse: To take arguments as key-value pairs, the input is first taken as a string, and using a python inbuilt method split() we are dividing it into two separate strings, here representing key and its value. In the next step, these made to fit into a dictionary form. 

Python3




#importing argparse module
import argparse
  
# create a keyvalue class
class keyvalue(argparse.Action):
    # Constructor calling
    def __call__( self , parser, namespace,
                 values, option_string = None):
        setattr(namespace, self.dest, dict())
          
        for value in values:
            # split it into key and value
            key, value = value.split('=')
            # assign into dictionary
            getattr(namespace, self.dest)[key] = value
  
# creating parser pbject
parser = argparse.ArgumentParser()
  
# adding an arguments 
parser.add_argument('--kwargs'
                    nargs='*'
                    action = keyvalue)
  
 #parsing arguments 
args = parser.parse_args()
  
# show the dictionary
print(args.kwargs)

Output: 

 



argparse command line

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :