Parse Command-Line Arguments

Medium ⏱ 12 min 57% acceptance ★★★★★ 4.6
CLI scripts receive arguments via sys.argv (index 0 is the script name). Write parse_args(argv) that takes such a list and returns a dict: first real argument is 'command', and any --key=value pairs become entries. Non-flag extras go into a 'targets' list.

Examples

Example 1
Input
parse_args(['tool.py', 'deploy', '--env=prod', 'web1', 'web2'])
Output
{'command': 'deploy', 'env': 'prod', 'targets': ['web1', 'web2']}
Explanation

argv[0] is skipped; flags and targets are separated.

Constraints

  • Skip argv[0].
  • Flags start with -- and contain =.
  • Missing command → return {}.

Topics

Modules & Packagessys.argv

Companies

CiscoIntelOracle

Hints

Hint 1

Slice argv[1:] before processing.

Hint 2

arg.startswith('--') and '=' in arg identifies flags.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.