How to split a semicolon-separated string to a dictionary in Python?

PythonServer Side ProgrammingProgramming

If you have strings like:

"Name1=Value1;Name2=Value2;Name3=Value3"

and you want to convert it to a dictionary, it is fairly easy. You could simply split on ';' and then on '=' and pass this to dict constructor. 

For example

>>> s = "Name1=Value1;Name2=Value2;Name3=Value3"
>>> dict(item.split("=") for item in s.split(";"))
{'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1'}
raja
Published on 18-Dec-2017 07:16:43
Advertisements