Skip to content

python args and dict usage

Since I use argparse a lot and also like to store some values in a nested dict this is my example.

import argparse

environments = {
    "development": {
        "account_id": "11111111111111111",
        "year": 2004
    },
    "production": {
        "account_id": "22222222222222222222",
        "year": 2007
    }
}

parser = argparse.ArgumentParser(description="A simple example.")

parser.add_argument("environment", help="environment to use")

parser.add_argument("-a", "--action", help="action to perform")

group = parser.add_mutually_exclusive_group()
group.add_argument("--list", action="store_true", help="list")
group.add_argument("--export", action="store_true", help="export")
group.add_argument("--migrate", action="store_true", help="migrate")

# Optional argument with a default value
#parser.add_argument("--output", default="out.txt", help="The output file (default: out.txt).")

# Optional argument with a boolean switch (action="store_true" makes it a flag)
#parser.add_argument("--verbose", action="store_true", help="Enable verbose output.")

args = parser.parse_args()

if args.environment not in ['development', 'production']:
    exit('try -h for args')
else:
    if args.list or args.export or args.migrate:
        print(f"environment: {args.environment} and account_id: {environments[args.environment]['account_id']}")
        #print(f"Output file: {args.output}")
        #if args.verbose:
        #    print("Verbose mode enabled.")
    else:
        print ('try -h for args need --list, --export or --migrate')