Computer >> Computer tutorials >  >> Programming >> Python

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


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'}