I know there are a lot of other posts about parsing comma-separated values, but I couldn\'t find one that splits key-value pairs and handles quoted commas.
I have st
Ok, I actually figured out a pretty nifty way, which is to split on both comma and equal sign, then take 2 tokens at a time.
input_str = '''age=12,name=bob,hobbies="games,reading",phrase="I'm cool!"'''
lexer = shlex.shlex(input_str)
lexer.whitespace_split = True
lexer.whitespace = ',='
ret = {}
try:
while True:
key = next(lexer)
value = next(lexer)
# Remove surrounding quotes
if len(value) >= 2 and (value[0] == value[-1] == '"' or
value[0] == value[-1] == '\''):
value = value[1:-1]
ret[key] = value
except StopIteration:
# Somehow do error checking to see if you ended up with an extra token.
pass
print ret
Then you get:
{
'age': '12',
'name': 'bob',
'hobbies': 'games,reading',
'phrase': "I'm cool!",
}
However, this doesn't check that you don't have weird stuff like: age,12=name,bob, but I'm ok with that in my use case.
EDIT: Handle both double-quotes and single-quotes.