Python Split Command Separated Key Value Pair With Quotes

Jul 3, 2019

Scenario 1: perfectly formatted value

import shlexvalue_str = 'name="Desmond Lua",age=40,gender=M,friends="James, Ramesh, K\'to, 小爱"'# posix=True - remove quotes of string in final values = shlex.shlex(value_str, posix=True)s.whitespace_split = Trues.whitespace = ', \n'data = dict(pair.split('=', 1) for pair in s)
{
    'name': 'Desmond Lua',
    'age': '40',
    'gender': 'M',
    'friends': "James, Ramesh, K'to, 小爱"
}

Scenario 2: whitespace and comma as separator

import shlexvalue_str = 'name="Desmond Lua",\tage=40, gender=M,\nfriends="James, Ramesh, K\'to, 小爱"'s = shlex.shlex(value_str, posix=True)s.whitespace_split = Trues.whitespace = ', \n\t'data = dict(pair.split('=', 1) for pair in s)

NOTE: This solution doesn't work if the is space in key-value pair (e.g. name = "Desmond Lua")

Scenario 3: spaces in key value pair

import shleximport revalue_str = 'name = "Desmond Lua" ,\tage=40, gender=M,\nfriends="James, Ramesh, K\'to, 小爱"'s = shlex.shlex(value_str, posix=True)s.whitespace_split = Trues.whitespace = ','p = re.compile(r'\s*=\s*')data = dict(p.split(pair.strip(), maxsplit=1) for pair in s)

NOTE: This assume the actual key/value doesn't have whitespace on left and right.

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.