Python: Key Value pair using argparse
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:
- 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.
- 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.
- 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.
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