String to a dictionary

EasyDictionary Programs · 54 of 94

Write a Python program to convert “key=value; key=value” text into a dictionary.

Advertisement
Input
"Apr=April; Mar=March"
Output
{'Apr': 'April', 'Mar': 'March'}

Approach

  1. Split on “;”, then split each part on “=” and strip spaces.

Solution

Python
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.

More dictionary programs

← All 94 Dictionary Programs

Leave a Comment