Python Practice › Dictionary Programs › Program 54
String to a dictionary
Write a Python program to convert “key=value; key=value” text into a dictionary.
Input
"Apr=April; Mar=March"
Output
{'Apr': 'April', 'Mar': 'March'}Approach
- Split on “;”, then split each part on “=” and strip spaces.
Solution
text = "Apr=April; Mar=March"d = dict(part.strip().split("=") for part in text.split(";"))print(d)Output
{'Apr': 'April', 'Mar': 'March'}Line by line
Line 2
strip() removes the space after each semicolon, so the second key is “Mar”, not ” Mar”.
Learn the concept
New to this topic? Read the lesson, then come back.