Last active
September 2, 2015 19:02
-
-
Save stavxyz/c82a27fc481902ff85ff to your computer and use it in GitHub Desktop.
delimited strings to dictionary. good for flexibly ingesting key value pairs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def kwargs(string, separator='=', type=None): | |
"""Return a dict from a delimited string. | |
If 'type' is not None, values will be passed through | |
to type before returning the dictionary. | |
""" | |
if separator not in string: | |
raise ValueError("Separator '%s' not in value '%s'" | |
% (separator, string)) | |
if string.strip().startswith(separator): | |
raise ValueError("Value '%s' starts with separator '%s'" | |
% (string, separator)) | |
kvps = {} | |
split = string.split(separator) | |
pairs = [split[0+i:2+i] for i in range(0, len(split)-1, 1)] | |
for i, (tkey, tvalue) in enumerate(pairs): | |
key = tkey.strip() | |
if i != 0: | |
key = key[key.rindex(' '):].strip() | |
value = tvalue.strip() | |
if i != (len(pairs) - 1): | |
value = value[:value.rindex(' ')].strip() | |
if key in kvps: | |
raise ValueError("Specified value for '%s' twice" % key) | |
if not value: | |
raise ValueError("No value for key '%s'" % key) | |
kvps[key] = value | |
if type is not None: | |
kvps = {k: type(v) for k, v in kvps.items()} | |
return kvps |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment