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
It's possible to do with a regular expression. In this case, it might actually be the best option, too. I think this will work with most input, even escaped quotes such as this one: phrase='I\'m cool'
With the VERBOSE flag, it's possible to make complicated regular expressions quite readable.
import re
text = '''age=12,name=bob,hobbies="games,reading",phrase="I'm cool!"'''
regex = re.compile(
r'''
(?P\w+)= # Key consists of only alphanumerics
(?P["']?) # Optional quote character.
(?P.*?) # Value is a non greedy match
(?P=quote) # Closing quote equals the first.
($|,) # Entry ends with comma or end of string
''',
re.VERBOSE
)
d = {match.group('key'): match.group('value') for match in regex.finditer(text)}
print(d) # {'name': 'bob', 'phrase': "I'm cool!", 'age': '12', 'hobbies': 'games,reading'}