optlist2dict

opthandler.optlist2dict(optlist, convert=False, **kwargs)[source]

Convert an option list to an option dictionary.

Parameters:
  • optlist (iterable) – The option list that should be converted to an option dictionary. Each option must start with a hyphen ('-') and must be a separate item of the list. Multiple values for the same option might be given as separate list items or one single list item.

  • convert (bool, optional) – If True, apply convert_str() on the values of the returned option dictionary. This will convert strings to their corresponding Python data types.

  • kwargs (dict, optional) – Keyword arguments to parse to convert_str().

Returns:

optdict (dict) – The resulting option dictionary. Each item of optlist that starts with '-' becomes a key in optdict. All following items that don’t start with '-' become the value of that key.

See also

shlex.join()

Convert an option list to an option string

optdict2list()

Convert an option dictionary to an option list

Examples

>>> optlist2dict(['-a', '0', '-b', '1'])
{'a': '0', 'b': '1'}
>>> optlist2dict([' -a', ' 0 ', ' -b ', '1 '])
{'a': '0', 'b': '1'}
>>> optlist2dict(['-a', '0', '-B', 'XyZ'])
{'a': '0', 'B': 'XyZ'}
>>> optlist2dict(['--ax', '0x', '---bxy', '1xy'])
{'ax': '0x', 'bxy': '1xy'}
>>> optlist2dict(['-a', '0', '-b', '1', '2'])
{'a': '0', 'b': '1 2'}
>>> optlist2dict(['-a', '0', '-b', '1 2'])
{'a': '0', 'b': '1 2'}
>>> optlist2dict(['-a', '0', '-b', '-c', '2'])
{'a': '0', 'b': '', 'c': '2'}
>>> optlist2dict(['arg1', 'arg2', '-b', '1'])
{'': 'arg1 arg2', 'b': '1'}
>>> optlist2dict([])
{}

Wrong input:

>>> optlist2dict(['-a 0', '-b 1'])
{'a 0': '', 'b 1': ''}