How do I convert a delimited string to a dictionary?

I tried to convert this string literal into dictionary object in python without success:

args = 'key_1=895, key_2=f.Comment'
args = args.replace("'","")
args = dict(args)

But I got an error:

ValueError: dictionary update sequence element #0 has length 1; 2 is required

I knew that my args is still one string as .replace() that I tried to remove single quote did not work. How ? Please kindly help me converting to dictionary object, I just want it as a result: {'key_1':895,'key_2':'f.Comment'}. Thanks

Answer

There are no single quotes in that string. Single quotes were only used to mark the beginning and end of a string literal; they are not part of the string itself.

To parse the string into a dictionary you can use the .split() method and a generator expression:

>>> dict(part.strip().split("=") for part in args.split(","))
{'key_1': '895', 'key_2': 'f.Comment'}

Leave a Reply

Your email address will not be published. Required fields are marked *