Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how do I turn a string of key-values to a proper dict in python?

Let’s say I have a dictionary as a string with an unknown number of spaces in between:

'address: 123 fake street city: new york state: new york population: 500000'

How do I get

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'address': '123 fake street',
 'city': 'new york',
 'state': 'new york',
 'population': 500000}

OR even lists or tuples to the effect of:

['address', '123 fake street'],
['city', 'new york'...]

(1) Assume keys are always single words with a colon

key:

city:

population:

(2) Assume edge cases where Address: may be "C/O John Smith @ Building X, S/W"

>Solution :

Try (regex101):

import re

s = "address: C/O John Smith @ Building X, S/W city: new york state: new york    population:        500000"

d = dict(re.findall(r"([^\s]+)\s*:\s*(.*?)\s*(?=[^\s]+:|$)", s))
print(d)

Prints:

{
    "address": "C/O John Smith @ Building X, S/W",
    "city": "new york",
    "state": "new york",
    "population": "500000",
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading