Python Program for Key Value pair using argparse

When developing Python applications, it's often necessary to create programs that accept key-value pairs as input arguments. Key-value pairs provide a flexible way to pass data to a program, allowing customization and parameterization. Python's argparse module simplifies the process of building command-line interfaces, including handling key-value pairs.

The argparse module offers a wide range of functionalities, including handling different types of arguments, providing usage messages, handling default values, and much more.

Basic Key-Value Parser Implementation

Let's create a simple program that accepts key-value pairs using argparse ?

import argparse

def main():
    parser = argparse.ArgumentParser(description='Key-Value Pair Parser')
    parser.add_argument('-k', '--key', type=str, help='Key')
    parser.add_argument('-v', '--value', type=str, help='Value')
    args = parser.parse_args()
    
    if args.key and args.value:
        print(f'Key: {args.key}')
        print(f'Value: {args.value}')
    else:
        parser.print_help()

if __name__ == '__main__':
    main()

This creates an ArgumentParser instance that accepts two optional arguments: -k (or --key) and -v (or --value). If both are provided, it displays them; otherwise, it shows the help message.

Making Arguments Required

To ensure both key and value are always provided, set the required parameter to True ?

import argparse

def main():
    parser = argparse.ArgumentParser(description='Key-Value Pair Parser')
    parser.add_argument('-k', '--key', type=str, help='Key', required=True)
    parser.add_argument('-v', '--value', type=str, help='Value', required=True)
    args = parser.parse_args()
    
    print(f'Key: {args.key}')
    print(f'Value: {args.value}')

if __name__ == '__main__':
    main()

Now argparse will automatically display an error message if either argument is missing.

Adding Validation

You can validate the format of keys or values using regular expressions ?

import argparse
import re

def main():
    parser = argparse.ArgumentParser(description='Key-Value Pair Parser')
    parser.add_argument('-k', '--key', type=str, help='Key', required=True)
    parser.add_argument('-v', '--value', type=str, help='Value', required=True)
    args = parser.parse_args()
    
    # Validate key format (alphanumeric only)
    key_pattern = re.compile(r'^[a-zA-Z0-9]+$')
    if not key_pattern.match(args.key):
        print('Error: Invalid key format. The key must be alphanumeric.')
        return
    
    print(f'Key: {args.key}')
    print(f'Value: {args.value}')

if __name__ == '__main__':
    main()

This example validates that the key contains only alphanumeric characters.

Handling Multiple Key-Value Pairs

For programs that need multiple key-value pairs, you can use the action='append' parameter ?

import argparse

def main():
    parser = argparse.ArgumentParser(description='Multiple Key-Value Pair Parser')
    parser.add_argument('-p', '--pair', nargs=2, metavar=('KEY', 'VALUE'), 
                       action='append', help='Key-value pair')
    args = parser.parse_args()
    
    if args.pair:
        key_value_dict = {}
        for key, value in args.pair:
            if key in key_value_dict:
                print(f'Warning: Duplicate key "{key}" found. Overwriting previous value.')
            key_value_dict[key] = value
        
        print('Key-Value Pairs:')
        for key, value in key_value_dict.items():
            print(f'Key: {key}, Value: {value}')
    else:
        print('No key-value pairs provided.')

if __name__ == '__main__':
    main()

This allows users to specify multiple pairs like: python script.py -p name John -p age 25

Error Handling

Add proper error handling to make your program more robust ?

import argparse
import sys

def main():
    try:
        parser = argparse.ArgumentParser(description='Key-Value Pair Parser')
        parser.add_argument('-k', '--key', type=str, help='Key', required=True)
        parser.add_argument('-v', '--value', type=str, help='Value', required=True)
        args = parser.parse_args()
        
        print(f'Key: {args.key}')
        print(f'Value: {args.value}')
        
    except KeyboardInterrupt:
        print('\nProgram interrupted by user.')
        sys.exit(1)
    except Exception as e:
        print(f'An error occurred: {str(e)}')
        sys.exit(1)

if __name__ == '__main__':
    main()

Usage Examples

Here are common ways to use these programs from the command line:

# Basic usage
python key_value_parser.py --key name --value John

# Short form
python key_value_parser.py -k age -v 25

# Multiple pairs (for the multi-pair version)
python multi_parser.py -p name John -p age 25 -p city "New York"

Conclusion

The argparse module provides a powerful and flexible way to handle key-value pairs in Python command-line applications. By implementing proper validation and error handling, you can create robust programs that gracefully handle user input and provide clear feedback when issues occur.

Updated on: 2026-03-27T12:29:30+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements